@Configuration
public class DanyConfig implements ApplicationContextAware {
private static ApplicationContext applicationContext=null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class DanyTest {
@Test
public void test(){
ConfigurableApplicationContext context = (ConfigurableApplicationContext) DanyConfig.getApplicationContext();
//Bean的实例工厂
DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) context.getBeanFactory();
//Bean构建 BeanService.class 要创建的Bean的Class对象
BeanDefinitionBuilder dataSourceBuider = BeanDefinitionBuilder. genericBeanDefinition(BeanService.class);
//向里面的属性注入值,提供get set方法
dataSourceBuider.addPropertyValue("msg", "hello ");
//dataSourceBuider.setParentName(""); 同配置 parent
//dataSourceBuider.setScope(""); 同配置 scope
//将实例注册spring容器中 bs 等同于 id配置
dbf.registerBeanDefinition("beanService", dataSourceBuider.getBeanDefinition());
BeanService beanService=(BeanService) context.getBean("beanService");
beanService.say();
}
}
class BeanService {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void say(){
System.out.println("====="+msg);
}
}
网友评论