ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring配置文件详解 (一)

2019-04-06 09:37:37  阅读:151  来源: 互联网

标签:配置文件 Autowired Spring Bean 详解 注解 声明 传统


1.<context:annotation-config/>
       

      在基于主机方式配置Spring时,Spring配置文件applicationContext.xml,你可能会见<context:annotation-config/>这样一条配置,它的作用是隐式的向Spring容器注册

                      AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor

                     PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor 

这4个BeanPostProcessor.注册这4个bean处理器主要的作用是为了你的系统能够识别相应的注解。   
      例如:

            如果想使用@Autowired注解,需要在Spring容器中声明AutowiredAnnotationBeanPostProcessor Bean。

传统的声明方式如下:

                  <bean class= "org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

            如果想使用@PersistenceContext注解,需要在Spring容器中声明PersistenceAnnotationBeanPostProcessor Bean。

传统的声明如下:

                  <bean class= "org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

             如果想使用@Required注解,需要在Spring容器中声明RequiredAnnotationBeanPostProcessor Bean。

传统声明方式如下:

                 <bean class= "org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

              如果想使用@Resource、@ PostConstruct、@ PreDestroy等注解就要声明CommonAnnotationBeanPostProcessor。

传统申明方式如下:
                  <bean class= "org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor" />

       所以,如果按照传统声明一条一条去声明注解Bean,就会显得十分繁琐。因此如果在Spring的配置文件中事先加上<context:annotation-config/>这样一条配置的话,那么所有注解的传统声明就可以被  忽略,即不用在写传统的声明,Spring会自动完成声明。



   

 2.<context:component-scan base-package="com.xx" /> 

 

 

        <context:component-scan/>的作用是让Bean定义注解工作起来,也就是上述传统声明方式。 它的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
        值得注意的是<context:component-scan/>不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此当使用  <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。

              

3.   @Autowired           
               

        @Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。@Autowired的标注位置不同,它们都会在Spring在初始化这个bean时,自动装配这个属性。注解之后就不需要set/get方法了。

标签:配置文件,Autowired,Spring,Bean,详解,注解,声明,传统
来源: https://www.cnblogs.com/anyiz/p/10660852.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有