手动注册单例bean:
@Autowired
private ApplicationContextUtil applicationContextUtil;
@PostConstruct
public void init() {
初始化需要注册的bean
MqConfig mqConfig = new MqConfig();
....
String beanName = "mqConfig";
try{
if (applicationContextUtil.getBean(beanName) != null) {
applicationContextUtil.destroySingleton(beanName);
}
} catch(Throwable e) {
log.warn("Bean {} not exist!", beanName);
}
applicationContextUtil.registerSingletonBean(beanName, mqConfig);
}
spring容器工具类:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ApplicationContextUtil {
@Autowired
private ApplicationContext applicationContext;
/**
* 动态注入单例bean实例
*
* @param beanName bean名称
* @param singletonObject 单例bean实例
* @return 注入实例
*/
public Object registerSingletonBean(String beanName, Object singletonObject) {
//将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
//获取BeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();
//动态注册bean.
defaultListableBeanFactory.registerSingleton(beanName, singletonObject);
//获取动态注册的bean.
return configurableApplicationContext.getBean(beanName);
}
public Object getBean(String beanName) {
try {
return applicationContext.getBean(beanName);
} catch (Throwable e) {
log.warn("getBean {} fail!", beanName, e);
return null;
}
}
public void destroySingleton(String beanName) {
//将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
//获取BeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();
defaultListableBeanFactory.destroySingleton(beanName);
}
}