SpringBoot Bean的动态管理
第一种方法:
第一步,先创建一个类,废话不多说
注入 ApplicationContext
@Configuration
public class BeanConfig {
@Autowired
private ApplicationContext ctx;
}
添加注册bean/删除bean方法
/**
* 动态注册bean
*
* @param target
* @param beanName
* @param <T>
* @return
*/
private <T> void registerBean(Class<T> target, String beanName) {
if (!ctx.containsBean(beanName)) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(target);
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
}
}
/**
* 动态删除bean
*
* @param beanName
*/
private void removeBean(String beanName) {
if (ctx.containsBean(beanName)) {
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
defaultListableBeanFactory.removeBeanDefinition(beanName);
}
}
添加定时任务,模拟bean添加与销毁,实际可以根据数据库配置,动态管理
@Scheduled(fixedRate = 10 * 1000, initialDelay = 0)
public void task() {
registerBean(DemoBean.class, "demoBean");
System.out.println(((DemoBean)ctx.getBean("demoBean")).hashCode());
registerBean(DemoBean.class, "demoBean");
System.out.println(((DemoBean)ctx.getBean("demoBean")).hashCode());
System.out.println(ctx.containsBean("demoBean"));
removeBean("demoBean");
System.out.println(ctx.containsBean("demoBean"));
}
第二种方法
使用注解@Conditional
@Component @Conditional(TaskCondition.class) public class OpenTask {}
创建 类TaskCondition 实现 Condition,实现matches方法
实际根据项目运行环境,加载对应的bean,
application.properties 中配置 system.environment=dev
/**
* 系统加载条件
*
* @author fighting
* @date 2018-06-21
*/
public class TaskCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String env = context.getEnvironment().getProperty("system.environment");
if (ENV.TEST.getEnv().equals(env) || ENV.PROD.getEnv().equals(env)) {
return true;
}
return false;
}
}
/**
* 运行环境
*/
public enum ENV {
TEST("test"), PROD("prod"), DEV("dev");
private String env;
public String getEnv() {
return env;
}
ENV(String env) {
this.env = env;
}
}