Spring中获取上下文的几种方式

  • 通过加载配置文件方式获取
//不是根目录下
ApplicationContext context = new FileSystemXmlApplicationContext("WebContent/WEB-INF/config/base/applicationContext.xml");
//根目录下
ApplicationContext context1 = new ClassPathXmlApplicationContext("applicationContext.xml");

 

  • 通过 WebApplicationContextUtils 的 getWebApplicationContext(servletContext) 获取,

使用该方法的必须依赖Servlet容器。

    public JsonResult edit(SysRoleEntity entity, HttpServletRequest request){
        ServletContext servletContext = request.getSession().getServletContext();
        ApplicationContext context =         WebApplicationContextUtils.getWebApplicationContext(servletContext);
        SysRoleService bean = context.getBean(SysRoleService.class);
        boolean modify = sysRoleService.modify(entity);
        return new JsonResult().ok(modify);
    }

 

  • 通过实现 ApplicationContextAware 接口的方式
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.context == null){
            SpringUtil.context = applicationContext;
        }
    }

    /**
     * 获取ApplicationContext
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

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

    public static <T> T getBean(Class<T> clazz){
        return getContext().getBean(clazz);
    }

}

重写 setApplicationContext(ApplicationContext applicationContext) 在 String 启动的时候 Spring 会帮我们装载

需要注意的是要把 SpringUtil 交给 Spring 管理 加个 @Component 注解 或者配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值