Spring注解

项目中通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。
Spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了 @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,需要打开以下配置信息:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <context:annotation-config/>
        <mvc:annotation-driven/>
        <!--控制器所在的包-->
        <context:component-scan base-package="com.mycontroller"/>

</beans>

<context:annotation-config/>的作用是向Spring容器注册以下四个BeanPostProcessor:

AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor

那么,为什么要注册这四个BeanPostProcessor呢?

<context:annotation-config/>的作用是向Spring容器注册以下四个BeanPostProcessor:
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor

那么,为什么要注册这四个BeanPostProcessor呢?
是为了让系统能够识别相应的注解。
例如:
1、如果想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。
传统声明方式如下:

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/>
需要注意的是Autowired只能注解接口,不能注解实现类。
2、如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor的Bean。
3、如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。
4、如果想使用@Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

以上这些注解是很常用的,如果按照传统的方式进行配置将会非常繁琐,所以Spring给我们提供了一个简便的方式:<context:annotation-config/>,使用该元素可以自动声明以上注解。
注:由于<context:component-scan base-package=”xxx.xxx”/>也包含了自动注入上述Bean的功能,所以此时的<context:annotation-config/> 可以省略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值