Develop/Spring framework

[Spring] Bean xml setting

자라선 2020. 7. 31. 11:21

1. DI xml

지금까지 의존성 주입을 위해 아래와 같은 DaoFactory 클래스를 만들었는데

매번 의존성 주입할때마다 DI용 클래스를 만들어주기 너무 번거롭고 JVM 특성상 컴파일 후 수정 하려면

재컴파일이 필요하기 때문에 효과적이지 못하다.

하지만 xml 로 의존성을 부여하며 bean를 생성할수 있다.

@Configuration
public class DaoFactory {
	@Bean
	public ConnectionMaker connectionMaker() {
		return new DConnectionMaker();
	}
	@Bean
	public UserDao userDao(){
		return new UserDao(connectionMaker());
	}
}

위 코드와 같이 @Configuration 과 @Bean 어노테이션을 사용하여 bean 생성을 해왔다.

이걸 아래와 같이 수정할 수있다.

  자바 코드 설정정보 XML 설정정보
빈 설정파일 @Configuration <beans>
빈의 이름 @Bean methodName() <bean id='methodName'
빈의 클래스 return new BeanClass(); class='com.spring.test.BeanClass'
빈의 의존 오브젝트 return new UserDao(connectionMaker()); <property id='connectionMaker' ref='connectionMaker'/>

그렇게 하여 적용한 applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       					http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id='connectionMaker' class='com.Spring.User.dao.DConnectionMaker' />
	
	<bean id='userDao' class='com.Spring.User.dao.UserDao'>
		<property name='connectionMaker' ref='connectionMaker' />
	</bean>
</beans>

@Configuraion은 <beans> 라는 태그가 되었고

@Bean 은 <bean>으로 <beans>태그 하위에 속해져있다는 것을 볼수 있다.

@Configuraion에는 이 밖에 속성을 주었는데 beans의 xml 값의 유효성 체크를 위해 DTD 나 schema등의 네임스페이스 셋팅할수 있다. 위의 코드의 경우 schema를 셋팅하여 주었다.(자세한건 다음에)

 

@Bean은 id는 메소드명이고 class는 가져오는 객체의 pull path를 작성하여준다.

하지만 의존성 부여를 위한 객체의 경우에는 <property> 태그가 추가로 붙었는데

name은 해당 해당 객체의 전역변수 변수명이 붙는다. 이때! setter(수정자)와 기본 생성자가 필수로 들어가야한다. 어차피 없으면 생성자나 setter 작성하라고 에러뜬다.

ref는 가져오는 bean를 작성하여주면되는데 저 코드에서는 앞서 connectionMaker를 생성하여 주었기 때문에

ref로 작성해주면 된다.

 

public class main {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//UserDao userdao = new DaoFactory().userDao();
		//ApplicationContext context = new AnnotationConfigApplicationContext(CountingDaoFactory.class);
		ApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml");
		UserDao userdao = context.getBean("userDao", UserDao.class);		
	}
}

GenericXmlApplicationContext 객체를 가져와 applicationContext.xml의 경로를 가져오자

/java/applicationContext.xml 의 위치에 두면 된다.

덤으로 GenericXmlApplicationContext 에 classpath기능을 첨부하여 만든 객체인

ClassPathXmlApplicationContext("daoContext.xml",UserDao.class); 으로도 사용할수 있다.