java/spring

[spring] 어노테이션을 이용한 스프링 설정

tea-tea 2024. 6. 9. 07:26
주제
스프링 컨테이너 설정 과정에서 xml대신 java파일에서 어노테이션을 이용하는 방법.
스프링 설정 파일의 분할 및 import 방법.

 

어노테이션 기반의 스프링 컨테이너 설정


스프링 컨테이너 설정파일은 xml 대신 java 파일로 대체 가능하다.

방법은 다음과 같다.

 

먼저 스프링 컨테이너 역할을 할 클래스를 생성하고 @Configuration을 클래스 상단에 명시한다.

다음, 빈 객체가 될 메소드를 만들고 메소드 상단에 @Bean을 명시한다.

빈 객체의 value는 메소드의 반환 타입이고, id는 이름이 된다.

 

예시(변경 전 xml 파일)

<?xml version="1.0" encoding="UTF-8"?>

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

	<context:annotation-config />

	<bean id="characterDAO" class="testPjt11.DAO.CharacterDAO"></bean>

	<bean id="registerService"
		class="testPjt11.service.RegisterService" init-method="initBeanEX1"
		destroy-method="destroyBeanEX1">
		<constructor-arg name="characterDAO"
			ref="characterDAO"></constructor-arg>
	</bean>
	<bean id="selectService" class="testPjt11.service.SelectService">
		<property name="characterDAO" ref="characterDAO"></property>
	</bean>


</beans>

 

어노테이션 스프링 컨테이너 설정(변경 후)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CharacterConfig {

	@Bean
	public CharacterDAO characterDAO() {
		return new CharacterDAO();
	}

	@Bean
	public RegisterService registerService() {
		return new RegisterService(characterDAO());
	}

	@Bean
	public SelectService selectService() {
		SelectService selectService=new SelectService();
		selectService.setCharacterDAO(characterDAO());
		return selectService;
		
	}

}

참고로, 위 코드에서는 각 서비스 객체에서 characterDAO를 호출하고 있어서 마치 여러 개의 characterDAO가 할당되는 것 같지만, 실제로는 @Configuration태그를 단 설정 파일 내부 객체들을 싱글톤으로 자동 구분되므로 단일한 객체가 만들어진다.

 

사용

package testPjt11;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import testPjt11.configuration.CharacterConfig;

public class Main2 {


	public static void main(String[] args) {
    	//xml 파일 가져오기(이전 방식)
		// GenericXmlApplicationContext ctx =
		// new GenericXmlApplicationContext("classpath:applicationContext.xml");    
    
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CharacterConfig.class);
		ctx.close();
	}
}

 

 

여러 파일을 분할해서 사용하는 경우


빈 설정 파일을 기능 별로 분리할 수 도 있다. 단, 이 때 공통 의존성이 생길 수도 있는데, 이는 다음 같이

autowired 같은 자동 주입 어노테이션으로 해결가능하다.

 

방식1: 배열

설정 파일을 분리 후, 사용 하는 곳에서 배열 형식으로 불러오는 방식

 

package testPjt11.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import testPjt11.DAO.CharacterDAO;
import testPjt11.service.RegisterService;
import testPjt11.service.SelectService;

@Configuration
public class CharacterConfig1 {

	@Bean
	public CharacterDAO characterDAO() {
		return new CharacterDAO();
	}


}
package testPjt11.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import testPjt11.DAO.CharacterDAO;
import testPjt11.service.RegisterService;
import testPjt11.service.SelectService;

@Configuration
public class CharacterConfig2 {

	@Autowired
	public CharacterDAO characterDAO;

	@Bean
	public RegisterService registerService() {
		return new RegisterService(characterDAO);
	}

	@Bean
	public SelectService selectService() {
		SelectService selectService=new SelectService();
		selectService.setCharacterDAO(characterDAO);
		return selectService;
		
	}

}

 

사용


public class Main3 {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext
        (CharacterConfig1.class,CharacterConfig2.class);
		ctx.close();
	}
}

 

 

방식2: import 방식

파일 분리 이후 하나의 설정 파일에 다른 빈 설정 파일을 import로 가져오는 방식이다.

이 역시 autowired 어노테이션으로 의존성 처리를 할 수 있다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({CharacterConfig1.class})
public class CharacterConfigImport {
	@Autowired
	public CharacterDAO characterDAO;

	@Bean
	public RegisterService registerService() {
		return new RegisterService(characterDAO);
	}

	@Bean
	public SelectService selectService() {
		SelectService selectService=new SelectService();
		selectService.setCharacterDAO(characterDAO);
		return selectService;
		
	}

}