빈 등록을 XML이 아닌 코드로 해야 할 일이 있어 찾아보니 DefaultListableBeanFactory를 이용하면 가능하다는 것을 알게 되었다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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...
'프로그래밍' 카테고리의 다른 글
@Async 사용 시 spring security 세션 정보 추출 주의사항 (0) | 2015.03.04 |
---|---|
@RequestMapping value에 property values 주입하기 (0) | 2014.12.05 |
Free Java Hotswap DCEVM (3) | 2014.09.01 |
이클립스 에러난 행으로 이동 (단축키) (0) | 2014.08.26 |
Resource files jar에 포함시키기 (META-INF/resources) (0) | 2014.07.25 |
HTTP multipart/form-data raw 데이터는 어떤 형태일까? (13) | 2014.06.30 |
My first Java8 Programming (0) | 2014.06.20 |
bean 엘리먼트의 parent attribute 사용 (0) | 2014.05.22 |