您的位置:首页 > 编程语言 > Java开发

Spring动态注册Bean

2017-06-13 00:00 337 查看
摘要: Spring动态创建Bean


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class DynamicConfiguration{
@Autowired
private ApplicationContext applicationContext;

[@Bean](https://my.oschina.net/bean)
public Integer registerMessageListener(){
AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();

//理论上这段代码执行不到,因为现在所有的bean生成都依赖DefaultListableBeanFactory
if(!(autowireCapableBeanFactory instanceof DefaultListableBeanFactory)){
String error = "applicationContext.getAutowireCapableBeanFactory() is not DefaultListableBeanFactory," +
"The current factory class is" + autowireCapableBeanFactory.getClass() +
",can not register message listener";

log.error(error);
throw new RuntimeException(error);
}

DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)autowireCapableBeanFactory;

//1.创建bean
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(UserService.class);

//2.设置属性
beanDefinitionBuilder.addPropertyValue("name", "myConfigure");
beanDefinitionBuilder.addPropertyValue("jdbcTemplate", applicationContext.getBean(JdbcTemplate.class));

//3.注册到spring
beanFactory.registerBeanDefinition(“userService”, beanDefinitionBuilder.getBeanDefinition());

log.info("register message listener success");

return 0;
}

}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息