BE전문가 프로젝트

4. Setter와 생성자 이용하여 설정하기(Spring Demo2) 본문

Spring 코딩

4. Setter와 생성자 이용하여 설정하기(Spring Demo2)

원호보고서 2021. 11. 21. 17:05

StudentClass생성

@Data //fullset
@RequiredArgsConstructor
@AllArgsConstructor
public class Student {
	private @NonNull String name;
	private @NonNull int age;
	private @NonNull ArrayList<String> hobbys;
	private double height;
	private double weight;
}

Data Annotation은 이전에 했던 Setter와 Getter등 여러가지 Annotation의 종합본이다.

RequiredArgsConstructor은 일부만 생성자로 이용하여 설정하고 싶을 때 사용하며 NonNull Annotaion을 이용하여 생성자로만 이용하고 싶은 변수를 설정하며 나머지 변수들은 Setter을 이용하여 변수를 설정한다.

 

StudentInfoClass생성

@Getter
@Setter
public class StudentInfo {
	private Student student;
}

 

ProductClass생성

@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Setter
@ToString
public class Product {
	private @NonNull String pName;
	private @NonNull int pPrice;
	private String maker;
	private String color;
}

 

 

xnl을 이용하여 bean 생성

xml파일생성(aapicationContext.xml)

<bean id="student1" class="com.example.Student">
		<constructor-arg value="백두산" />
		<constructor-arg value="25" />
		<constructor-arg>
			<list>
				<value>독서</value>
				<value>영화감상</value>
				<value>요리</value>
			</list>
		</constructor-arg>
		<property name="height" value="165" />
		<property name="weight">
			<value>45</value>
		</property>
	</bean>

	<bean id="studentInfo1" class="com.example.StudentInfo">
		<property name="student">
			<ref bean="student1" />
		</property>
	</bean>

studentInfo1에는 student1 Bean을 참조하여 set해준다

 

xml파일생성(aapicationContext2.xml)

<bean id="student3" class="com.example.Student">
		<constructor-arg value="한라산" />
		<constructor-arg value="50" />
		<constructor-arg>
			<list>
				<value>노래부르기</value>
				<value>게임</value>
			</list>
		</constructor-arg>
		<property name="height" value="175" />
		<property name="weight">
			<value>75</value>
		</property>
</bean>
    
<bean id="product" class="com.example.Product" 
		c:pName="Computer" c:pPrice="2000000" p:maker="Samsung">
	<property name="color" value="Yellow" />
</bean>

NameSpaces를 클릭하여 C와P를 추가하면 constructor-arg와 property를 c,p로 설정이 가능하다.

 

Main class

public class Main {
	public static void main(String[] args) {
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml"
        							,"classpath:applicationContext2.xml");
		Student student1 = (Student)ctx.getBean("student1");
		Student student3 = ctx.getBean("student3", Student.class);
		
        Product computer = ctx.getBean("product", Product.class);
		
        System.out.println(student1);
		System.out.println(student3);
		System.out.println(computer);
	}
}

Api에서 GenericXmlApplicationContext를 찾아보면 String ...이라고 적혀있는데 이것은 여러개의 xml파일을 읽어올 수 있다는 의미를 지니고 있다.  아이디는 고유값이기 때문에 같은 값은 넣으면 안된다.

 

Annotation을 이요하여 bean생성

Appicationconfig class

@Configuration
public class ApplicationConfig {

	@Bean
	public Student jimin() {
	ArrayList<String> hobbies = new ArrayList<String>();
	hobbies.add("게임"); hobbies.add("영화감상"); hobbies.add("여행");
	Student jimin = new Student("박지민", 24, hobbies);
	jimin.setHeight(172.5); jimin.setWeight(58);
	return jimin;
	}
	
	@Bean
	public StudentInfo info() {
		StudentInfo info = new StudentInfo();
				info.setStudent(this.jimin());
				return info;
	}
}

Appicationconfig2 class

@Configuration
public class ApplicationConfig2 {
	
	@Bean
	public Student younghee() {
		ArrayList<String> hobbies = new ArrayList<String>();
		hobbies.add("축구"); hobbies.add("UFC");
		Student younghee = new Student("이영희", 34, hobbies);
		younghee.setHeight(158.2);
		younghee.setWeight(46.2);
		
		return younghee;
	}
	@Bean
	public Product pencil() {
		Product pencil = new Product("연필", 200);
		pencil.setMaker("모나미"); pencil.setColor("black");
		return pencil;
	}
}

Annotaion을 이용하여 두개의 class에 bean을 생성한다.

 

public class Main2 {
	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class,
        					ApplicationConfig2.class);
		StudentInfo info = ctx.getBean("info", StudentInfo.class);
		System.out.println(info.getStudent());
		Student younghee = ctx.getBean("younghee", Student.class);
		System.out.println(younghee);
		System.out.println(info.getStudent());

	}
}

이것도 xml과 마찬가지로 api에서 Class...을 찾을 수 있다. 따라서 한개이상의 클래스에서 bean의 정보를 가져올 수 있다는 것을 뜻한다.

getbean을 이용하여 가져온 후 출력

Comments