Spring之ApplicationContext的获取

Spring上下文(ApplicationContext)的获取有三种方式。

   1.通过WebApplicationUtils工具类获取。WebApplicationUtils类是在Spring框架基础包spring-web-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用该方法的必须依赖Servlet容器。 使用方法如下: 

ApplicationContext ap =WebApplicationUtils.getWebApplicationContext(servletContextParam)

     其中servletContextParam是你需要传入的Servlet容器参数。

     2. 通过ClassPathXmlApplicationContext类获取。ClassPathXmlApplicationContext 类是在Spring框架基础包spring-context-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用方法如下:

ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");

     其中applicationContext.xml文件放在src下面,这样就保证可以读取到该文件。这个XML的作用是集中配置和管理所有Bean。

    applicationContext.xml代码: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        //中间部分是你自己配置的所有bean
</beans>

  3.创建一个自己的工具类(SpringContextHolder)实现Spring的ApplicationContextAware接口。实现代码如下:

@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;
 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    
    public static ApplicationContext getApplicationContext() {
        return context;
    }
}

总结:方式1要依赖Servlet容器,方式2实际只适合测试使用,方式1,2都有明显弊端。建议使用方式3。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值