Spring学习三-ApplicationContext

14 篇文章 0 订阅

Spring中的Resource接口

在Spring内部实现机制,针对于资源文件(配置的xml文件)有一个统一的接口Resource。

Resource具体实现类:

  1. ClassPathResource:类路径下的资源,位置在classes路径下
  2. FileSystemResource:文件系统资源,资源以文件系统路径的方式表示,如:D:/File/conf.xml;
  3. InputStreamResource:对应一个InputStream的资源
  4. ServletContextResource:访问web容器上下文中资源的类,负责以相对于web应用根目录的路径加载资源,支持以流和URL的方式访问。
  5. UrlResource :用户能够访问任何可以通过URL表示的资源。如http资源,ftp资源。

Spring的资源类型的地址前缀

地址前缀对应资源类型

  • classpath:从类路径中加载资源,相对于类的根路径。
  • file:使用URLResource从文件系统目录中装载资源。
  • http://:使用URLResource从web服务器中装载资源。
  • ftp://:使用URLResource从ftp服务器中装载资源。
  • 无前缀:根据ApplicationContext具体实现类采用对应类型的Resource。
    在web项目中可以使用Resource 来代替java的IO来获取资源,并且还支持Ant通配符。
    Ant风格:
  • ?:匹配文件名中的一个字符.
  • *:匹配文件命中的任意字符.
  • ** :匹配多层路径.
    示例:
 PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] res = resolver.getResources("classpath:/test.txt");
            for (Resource  resource : res){
       System.out.println(resource.getDescription()+"----"+resource.getFilename());
                //System.out.println(resource.getFile().);
                BufferedReader bf = new BufferedReader(new FileReader(resource.getFile()));
                String data = "";
                while((data = bf.readLine())!=null){
                    System.out.println(data);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != bf)bf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

输出结果

class path resource [test.txt]----test.txt
springResource加载

BeanFactory和ApplicationContext

BeanFactory

BeanFactory 是延迟加载,如果bean的某一属性没有注入,BeanFactory加载后,直到调用getBean方法的时候才会抛出异常,而ApplicationContext在初始化的时候会进行校验,这样有利于检查依赖的属性是否注入。且ApplicationContext继承自Beanfactory,其实现更为丰富,故通常我们选择使用ApplicationContext。
初始化Beanfactory的例子:

     //调用资源加载器加载Spring配置文件
        PathMatchingResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
        Resource res =resolver.getResource("classpath:/applicationContext.xml");
        DefaultListableBeanFactory bf =new DefaultListableBeanFactory();
        //BeanDefinition 读取器,专门读取资源到容器
        XmlBeanDefinitionReader reader =new XmlBeanDefinitionReader(bf);

        //读取资源进到容器
        reader.loadBeanDefinitions(res);

        //此时容器初始化完毕后可以取里面的bean了.
        bf.getBean("car");

ApplicationContext

主要类和接口
ApplicationEventPublisher: 让容器拥有发布应用程序上下文事件的功能.
ResourcePatternResolver:实现了类似于资源加载器的功能,能够识别特定前缀加Ant风格的路径并加载到容器中.
LifeCycle:管理容器中bean的生命周期。
ConfigurableApplicationContext:主要新增了refresh()和close()方法,让ApplicationContext有用了启动,关系和刷新上下文的功能。
ClassPathXmlApplicationContext与FileSystemXmlApplicationContext:Spring提供的两个常用的ApplicationContext实现类,前者默认从类路径加载配置文件,后者从文件系统加载。
然后初始化一个ApplicationContext看看:

ApplicationContext ac =new ClassPathXmlApplicationContext("application.xml");
ApplicationContext ac =new FileSystemXmlApplicationContext(/User/Desktop/application.xml);

ClassPathXmlApplicationContext如果没有前缀默认就是classpath: FileSystemXmlApplicationContext如果没有前缀默认就是 file:
Spring容器不仅可以通过xml来初始化,也可以通过@Configuration注解来注册Bean,Spring也提供了相应的AnnotationConfigApplicationContext。

ApplicationContext context =new AnnotationConfigApplicationContext(Config.class);

其中Config类就是加了@Configuration的类.

###WebApplicationContext
WebApplicationContext是Spring专门为web应用准备的,它可以从现对于web根目录的路径中装配文件来完成初始化。WebApplicationContext与ServletContext可以相互获得.
在非Web应用的环境下,Bean只有singleton和prototype两种作用域,而WebApplicationContext为Bean添加了三个新的作用域:request,session,global session。

WebApplicationContext和ServletContext是如何相互获取的,其实很简单,在WebApplicationContext里有ServletContext成员变量,直接get就完了。在ServletContext里有一个写死的attrbute,也是直接get…而且Spring提供了一个WebApplicationContextUtils来封装了这个写死的attribute.

其实就是直接调用了ServletContext.getAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
        return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }

WebApplication的初始化
初始化的方式有两种:

  1. 在web.xml中配置一个ContextLoaderListener;

  2. 配置一个自启动的LoaderServlet

  <!-- 加载spring容器 -->
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:spring/applicationContext-*.xml</param-value>
 </context-param>
 <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

不根据xml启动Spring而使用@Configuration类启动

  <context-param>
   <param-name>contextClass</param-name>
   <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 </context-param>
 <!-- 加载spring容器 -->
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>com.zdy.Configuration</param-value>
 </context-param>
 <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

配置一个contextClass参数ApplicationContext改为AnnotationConfigWebApplicationContext,然后contextConfigLocation不是指定配置文件xml位置了,改为指定Configuration类的位置。就OK了。

来源:我又不是架构师

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值