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를 사용 하는 경우도 발생할수 있다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

예를 들면 아래와 같다.

@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

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
126 Creating a CRUD REST API/Service with Spring Boot, JPA and Hibernate file 졸리운_곰 2018.08.17 147
125 Spring boot에서 REST API 개발 시작해보기 file 졸리운_곰 2018.08.17 350
124 [JSP] 네이버 스마트 에디터 연동 + 이미지파일 업로드 기능 추가 file 졸리운_곰 2018.07.28 1123
123 Use React and Spring Boot to Build a Simple CRUD App file 졸리운_곰 2018.07.28 385
122 JSP CRUD Example jsp 기본예제 file 졸리운_곰 2018.07.28 166
121 스웨거 2.0으로 스프링 부트 어플리케이션 API 문서화하기 file 졸리운_곰 2018.05.24 132
120 Spring REST API 문서를 Swagger로 만들자 file 졸리운_곰 2018.05.22 411
119 Spring REST API에 Swagger 2 설정하기 file 졸리운_곰 2018.05.22 335
118 Spring Boot와 AngualrJS를 조합한 코드 자동 생성 도구(scaffolding) file 졸리운_곰 2018.05.17 141
» Spring java Code 기반 설정 Configuration 어노테이션과 Bean 어노테이션 졸리운_곰 2018.05.14 77
116 java spring redis 세션 공유 : Spring Session을 이용한 세션 클러스터링 졸리운_곰 2018.05.06 1041
115 Spring MVC hello world example file 졸리운_곰 2018.05.04 223
114 Create a Web Application With Spring Boot file 졸리운_곰 2018.05.03 142
113 Spring Boot and JSP Tutorial file 졸리운_곰 2018.05.03 427
112 Spring Boot Hello World Example – JSP file 졸리운_곰 2018.05.03 109
111 Spring Boot – JSP View Example file 졸리운_곰 2018.05.03 137
110 SpringMVC-JSP 프로젝트를 Spring Boot로 옮기기 file 졸리운_곰 2018.05.03 319
109 SPRING BOOT에서 JSP 사용하기 졸리운_곰 2018.05.03 65
108 MYBATIS 기본 - SELECTLIST file 졸리운_곰 2018.03.26 79
107 Spring MVC 에 MyBatis 적용해 보기. file 졸리운_곰 2018.03.26 94
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED