spring启动加载类,手动加载bean
方法一:
public final class Assembler implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Assembler.beanFactory = beanFactory;
initMerchant();
}
实现该接口,可以在spring的bean创建之前,修改bean的定义属性。
也就是说,Spring允许BeanFactoryPostProcessor在容器实例化任何其它bean之前读取配置元数据,并可以根据需要进行修改
手动注册bean:
private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
DefaultListableBeanFactory beanFactory2 = (DefaultListableBeanFactory) beanFactory;
BeanDefinitionBuilder beanMer = BeanDefinitionBuilder.genericBeanDefinition(className);
beanMer.setParentName(beanType);
beanMer.addPropertyValue("mrchCode", corgNum);
beanMer.addPropertyValue("connectionName", beanName);
beanMer.setInitMethodName("init");
beanMer.setInitMethodName("isMerchantOpen");
beanName = beanType + "_" + corgNum;
beanFactory2.registerBeanDefinition(beanName, beanMer.getRawBeanDefinition());
方法二:
public class InitConfig extends HttpServlet implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
logger.info("销毁。。。。");
timer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
logger.info("初始化。。。。");
//手动让spring容器管理此类
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>jsfirst.weixin.InitConfig</listener-class>
</listener>