Spring java Code 기반 설정 Configuration 어노테이션과 Bean 어노테이션
2018.05.14 15:04
Spring java Code 기반 설정
Spring JavaConfig 프로젝트라는 것이 있다. 이는 프로젝트 XML 이 아닌 java 코드를 이용하여 컨테이너를 설정할 수 있는 기능을 제공하는 프로젝트로. 이를 이용하면 XML 이 아닌 자바코드를 이용하여 생성할 빈 객체 그리고 각 빈과의 연관등을 처리 할수 있는 방법이다.
1. Configuration 어노테이션과 Bean 어노테이션
org.springframework.context.annotation 의 Configuration 어노테이션과 Bean 어노테이션 코드를 이용하여 스프링 컨테이너에 새 로운 빈 객체를 제공할 수 있다.
@Configuration
public class SpringConfig {
@Bean
public Greet greet(){
return new Hello();
}
}
위 source에서 @Bean 어노테이션은 새로운 빈 객체를 제공할때 사용되며 아래 XML 과 동일한 설정이다.
<bean id="greet" class="com.interwater.Hello" />
만약 bean id를 greet 가 아닌 다른 것으로 변경하고 싶다면 @Bean(name="hello") 와 같이 설정하면 된다.
이러한 방식으로 생성된 각 빈간의 의존 관계는 메서드를 호출 함으로써 의존 관계를 설정할수 있다.
@Configuration
public class SpringConfig {
@Bean
public Greet greet(){
Hello hello= new Hello();
hello.setGreet(defaultGreet());
return hello
}
@Bean
public HiGreet defaultGreet(){
return new DefaultHiGreet();
}
}
또한 @Bean 어노테이션의 autowire 속성을 이용하여 연관 자동 설정을 할수 있다.
<bean name="helloService" class="com.interwater.helloServiceImpl" autowire="byName" />
위 코드는 아래 코드로 설정할수 있다.
@Configuration
public class SpringConfig {
@Bean(autowire = Autowire.BY_NAME)
public GreetController greetController(){
GreetController greetController = new GreetController();
...
return new Hello();
}
}
Autowire 방식은 BY_NAME(이름을 통한 자동 연관), BY_TYPE(type을 통한 자동 연관) 이렇게 2가지가 있으며 NO로 설정할 경우 자동 연관 처리를 하지 않는다.
2. @Configuration 어노테이션 설정정보 사용
위에서 적용된 어노테이션을 프로그램에 활용하기 위해서는 2가지 방법이 있다. 첫째로는 AnnotationConfigApplicationContext를 이용하는 방법이 있다.
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(GreetConfig.class);
GreetController greetController = context.getBean("homeController", HomeContriller.class);
....
}
두번째 방법으로 xml 설정을 활용하는 방법이 있다.
<bean class="org.springframework.context.annotation.ConfigurationClassPostProcessor" />
<bean class="com.interwater.GreetConfig"/>
또는
<context:annotation-config/>
<bean class="com.interwater.GreetConfig"/>
그리고 ImportResource를 통해서 Configuration 설정 클래스에서 xml 를 활용할수도 있다. @configuration 어노테이션 바로 하단에 아래 코드를 넣어 주면 된다.
@importResource({"classpath://greet-repository.xml", "classpath://greet-datasource.xml"})
3. Configuration 어노테이션 클래스 간의 의존
프로그램 규모 또는 개발 상황에 따라서 2가지 이상의 Configuration를 사용 하는 경우도 발생할수 있다.
예를 들면 아래와 같다.
@Configuration
public class GreetConfig {
@Bean
public Greet greet(){
Hello hello= new Hello(defaultGreet());
return hello
}
}
@Configuration
public class DefaultGreetConfig {
@Bean
public HiGreet defaultGreet(){
return new DefaultHiGreet();
}
}
위 source는 GreetConfig 의 greet 에서 defaultGreet 라는 bean을 사용 하는 경우이다. 이러한 경우 아래와 같이 Autowired 방법을 사용하거나 Import 어노테이션을 통해서 처리 될수 있다.
--- Autowired ---
@Configuration
public class GreetConfig {
@Autowired
private DefaultGreetConfig defaultGreetConfig;
@Bean
public Greet greet(){
Hello hello= new Hello(defaultGreetConfig.defaultGreet());
return hello
}
}
--- import ---
@Configuration
@Import({DefaultGreetConfig .class})
public class GreetConfig {
@Bean
public Greet greet(){
Hello hello= new Hello(defaultGreet());
return hello;
}
}
4. initMethod , destoryMethod
앞서 Spring xml 설정에서 init 과 destory 설정을 통해서 초기화/종료 메서드를 지정할수 있음을 알게 되었다. java Code기반 설정에서는 InitMethod , destoryMethod를 통해서 지정 / 처리 가능하다.
@Bean(initMethod="init")
위 구분을 넣으며 init method르 초기화시 활용하게 된다.
5. scope, Qualifier 어노테이션
Bean 어노테이션 하단에 Scpoe 어노테이션을 넣음으로 해서 scpoe 처리 및 proxyMode 처리가 가능하다. 또한 Qualifier 어노테이션을 통해서 두개이상의 빈객체에서 한정자를 활용하여 어느 특정빈을 선택하는 방법도 가능하다.
이는 앞선 포스트에 설명하였으므로 생략 하도록 한다.
[출처] https://github.com/kenu/springstudy2013/blob/master/0325/5.javaCodeConfig.md
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.

