---
title: "Spring注解学习笔记"
author: "fishswing"
date: "2012-06-07T13:51:01Z"
tags: []
categories: ["编程语言"]
slug: "spring"
draft: false
lastmod: "2012-06-07T14:03:57Z"
id: 1554361
url: "https://fishswing.iteye.com/blog/1554361"
---

本人最近因为项目需要使用Spring的注解功能，就在网上找了些资料看看，觉得Spring的注解没那么高深，也很简单的，下面把本人学习的成果整理了一下，供有需要的朋友参考一下。因为初次使用，可能有些地方写得不对，请高手谅解并指正一下哦。

 

1、环境框架：webwork2+spring2.5+hibernate3.3(webwork2可以换成struts2哦)

2、需引入common-annotations.jar包（因为 @Resource注解需要用到此包）

3、webwork2中的action需要使用spring来注入的话，需要在webwork.properties文件中配置webwork.objectFactory=spring(而且不光是Action的注入，涉及Action类中的业务类的注入也需要配置此项，否则报错)

4、spring的基本配置此外省略，只讲注解的配置

5、要使用注解功能，需要在spring的配置文件中加入context命令空间和schema的位置：（在beans中配置）

 

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

        <context:annotation-config/>
     
        ........
</beans>
```

 

 

 并配置&lt;context:annotation-config/&gt;来简化配置，该配置默认注册了AutowiredAnnotationBeanPostProcessor， CommonAnnotationBeanPostProcessor，PersistenceAnnotationBeanPostProcessor 以及equiredAnnotationBeanPostProcessor

   这四个BeanPostProcessor。（如果不这样配置，则将分别配置各种注解的Bean）

6、通过以上配置，就可以使用 @Autowired, @Qualifier， @Resource, @PostConstruct, @PreDestroy等注解了。

@Autowired 按类型自动装配

@Qualifier 只能和 @Autowired结合使用。作用是：在Autowired进行装配时，同时有两个（或以上的）同一类型的Bean配置时，使用 @Qualifier("bean的id")指定注入的名称，使 @Autowired从按类型注入转为按名称注入

@Resource  默认按名称进行装配，如果装配不了，则按类型装配（推荐使用 @Resource来替代 @Autowired）

@PostConstruct  配置在方法上（只能配置在方法上），表示在创建Bean之后将执行的方法

@PreDestroy  配置在方法上（只能配置在方法上），表示在销毁Bean之前将执行的方法

7、以上注解的使用，我们都需要在spring配置文件中配置相应的bean,完成byType和byName的注入。要将bean从配置文件完全移除，可以使用 @Component注释来实现零配置

8、spring2.5在 @Repository的基础上增加了 @Component, @Service, @Controller三个注解，都是标类的（把类配置为bean），分别用于不同的层次:

       @Component  泛化的概念，表示一个组件（Bean）,可作用在任何层次（也即如果不能确定层次时使用）

       @Service    作用于业务层的类

       @Controller  作用于控制层的类

       @Repository  作用于数据访问层的类

   通过在类上使用 @Repository、 @Component、 @Service 和 @Constroller 注解，Spring 会自动创建相应的 BeanDefinition 对象，并注册到 ApplicationContext 中。这些类就成了 Spring 受管组件。

9、使用 @Component注解后，spring容器必须使用类扫描机制以启用注释驱动Bean定义和注释驱动Bean的自动注入策略。则必须在spring的配置文件中添加如下配置：

&lt;context:component-scan base-package="com.free"/&gt;    (将会扫描com.free及其子包中的所有类)

10、对类进行扫描时，可以配置扫描指定的包和排除的包。有正则表达式、AspectJ、类和注释等的过滤类型如：

```
<context:component-scan base-package="com.free">
	    <context:include-filter type="regex" 
		expression="com\.free\.service\..*"/>
	    <context:exclude-filter type="aspectj" 
		expression="com.free.util..*"/>
	</context:component-scan>
```

 

11、有以下情况也不能完全摒除XML的配置方式：

a、Bean不是自己编写的，如JdbcTemplate或SessionFactory等，必须使用XML进行配置

b、注释往往是类级别的，而XML则更加灵活。比如相比于 @Transaction 事务注释，使用 aop/tx 命名空间的事务配置更加灵活和简单。

c、如果 Bean 的依赖关系是固定的，（如 Service 使用了哪几个 DAO 类），这种配置信息不会在部署时发生调整，那么注释配置优于 XML 配置；反之如果这种依赖关系会在部署时发生调整，XML 配置显然又优于注释配置，因为注释是对 Java 源代码的调整，您需要重新改写源代码并重新编译才可以实施调整。