栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

非spring容器管理的模块里使用bean(借助ApplicationContextAware和WebApplicationContextUtils)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

非spring容器管理的模块里使用bean(借助ApplicationContextAware和WebApplicationContextUtils)

#RT,废话不多说直接进入主题:
        在spring中通常采取注入的方式获取bean,比如

    @Resource
    private SystemConfig systemConfig;

    @Autowired
    private OssService coreConfig;

前提是使用这些注解的类也要纳入spring容器进行管理比如加上注解@Component。

但是,有时候需要在非spring管理的模块里使用bean,比如工具类Untils等。这种情况获取bean的方法有多种,在此只介绍其中之二,

一:借助ApplicationContextAware接口

        编写一个实现ApplicationContextAware接口,这个接口只有一个方法

void setApplicationContext(ApplicationContext var1) throws BeansException;

代码示例:

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static  T getBean(Class clazz){
        return applicationContext.getBean(clazz);
    }

    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

}

在spring容器加载的时候会执行setApplicationContext方法,拿到ApplicationContext(spring上下文),再通过applicationContext拿到bean,如:

    SystemConfig bean = SpringUtils.getBean(SystemConfig.class)

二:借助spring的工具类WebApplicationContextUtils

代码示例如下:

//普通类中
        ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        //使用request
        ServletContext sc = request.getServletContext();
        //通过webApplicationContextUtils获取ApplicationContext
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
        SystemConfig bean = ac.getBean(SystemConfig.class);

这种方法其实也是通过获取spring上下文ApplicationContext来拿到bean的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/671337.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号