BE전문가 프로젝트

5. xml과 Annotation을 동시에 이용하여 설정하기(StringDemo4) 본문

Spring 코딩

5. xml과 Annotation을 동시에 이용하여 설정하기(StringDemo4)

원호보고서 2021. 11. 22. 00:11

Stundent Class생성

@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class Student {
	private @NonNull String name;
	private @NonNull int age;
	private @NonNull List<String> hobbies;
	private double height;
	private double weight;
	}

name, age, bobbies는 생성자, height와 weight는 set으로 만든다.

 

주가 xml이고 서브가 Annotation인 경우

AppincationConfig 생성

@Configuration
public class ApplicationConfig {
	@Bean
	public Student student1() {
		Student student1 = new Student("ȫ����", 44, Arrays.asList("����", "���", "�ٵ�"));
		student1.setHeight(168);
		student1.setWeight(45);
		return student1;
	}
}

@student1의 정보를 가지고 있는 bean을 생성한다.

 

 

appicationContext.xml 파일 생성

<bean class="org.springframework.context.annotation.ConfigurationClassPostProcessor" />
	<bean class="com.example.ApplicationConfig" />

제일 처음에 사용한 bean에 클래스를 사용해야 anntaion으로 설정한 내용을 가져올 수 있으며, 실제로 bean객체를 생성했던 클래스를 이용한다는 의미를 지니고 있다.

 

main 클래스 생성

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

출력을 해보면 Application에 설정한 bean을 가져올 수 있다

 

주가 annotation이고 서브가 xml인 경우

applicationconfig.xml 생성

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="jojo" class="com.example.Student"
		c:name="조조" c:age="26" c:hobbies="캠핑, 영화시청, 게임" p:height="189.7" p:weight="88"/>
</beans>

context c, p를 이용하여 bean을 생성한다(namespace에서 가능).

 

ApplicationConfig2.class 클래스 생성

@Configuration
@ImportResource("classpath:applicationContext2.xml")
public class ApplicationConfig2 {
}

이전과는 다르게 @ImportResouse라는 Annotation을 사용하는데 위에서 xml이 주로 사용하는 경우에서 <bean class="org.springframework.context.annotation.ConfigurationClassPostProcessor" />의 역할을 ImportResoure Annotaion이 수행한다(applicationContext2.xml의 bean을 가져올 수 있다).

 

Main 클래스 생성

public class Main2 {
public static void main(String[] args) {
	ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig2.class);
	Student jojo = ctx.getBean("jojo",Student.class);
			System.out.println(jojo);
}
}
Comments