spring工程中得到注入bean的集中方式

来源:互联网 发布:大数据的四大特征 编辑:程序博客网 时间:2024/05/21 10:06
1、该方法不适用于获取注入的bean,没有解决(用注入方式注入的bean)
public class SpringApplicationContextUtil implements ApplicationContextAware{
    public static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringApplicationContextUtil.applicationContext=applicationContext;
    }
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
}
2、

public class SpringUnitl {

    public static <T> T getBean(String beanName){
        WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
        return (T)web.getBean(beanName);
    }
}
3、
public class SpringUnitl  implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
            throws BeansException {
        SpringUnitl.beanFactory = beanFactory;
    }
    public static BeanFactory getBeanFactory() {
        return beanFactory;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }
    
}
0 0
原创粉丝点击