스프링 빈 등록 (Java 코드 이용)

빈 등록을 XML이 아닌 코드로 해야 할 일이 있어 찾아보니 DefaultListableBeanFactory를 이용하면 가능하다는 것을 알게 되었다.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring.xml"})
public class RegisterBean {
@Autowired
private ApplicationContext context;
@Test
public void registBean() {
// get BeanFactory from ApplicationContext
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) context).getBeanFactory();
// 멤버 필드 값 셋팅
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.addPropertyValue("prop1", "prop1");
propertyValues.addPropertyValue("prop2", "prop2");
// bean 생성
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(Test1.class);
beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
beanDefinition.setPropertyValues(propertyValues);
// factory에 bean 등록
factory.registerBeanDefinition("test1", beanDefinition);
Test1 test = context.getBean(Test1.class);
assertThat("method1", is(test.method1()));
assertThat("method2", is(test.method2()));
String namkyu = context.getBean("namkyu", String.class);
assertThat("test_namkyu", is(namkyu));
}
}
@Data
class Test1 {
private String prop1;
private String prop2;
public String method1() {
return "method1";
}
public String method2() {
return "method2";
}
}


스프링 웹 애플리케이션을 구동하면 다음과 같이 DefaultListableBeanFactory 클래스에서 생성된 빈 정보를 출력하는 것을 확인 할 수 있다.

[2014-08-13 13:12:09 INFO  o.s.b.f.s.DefaultListableBeanFactory][598] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7c24d3f1: defining beans [loggingAOP,scheduleTest,applicationContextHolder,mailHandler,EHCacheService,userValidator,userDAO...