读书人

spring注脚

发布时间: 2012-08-30 09:55:54 作者: rapoo

spring注解

1. 使用Spring注解来注入属性
1.1. 使用注解以前我们是怎样注入属性的
类的实现:

?spring注脚?spring注脚



1.2. 引入@Autowired注解(不推荐使用,建议使用@Resource)
类的实现(对成员变量进行标注)

?spring注脚?spring注脚?spring注脚


@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。以上两种不同实现方式中,@Autowired的标注位置不同,它们都会在Spring在初始化userManagerImpl这个bean时,自动装配userDao这个属性,区别是:第一种实现中,Spring会直接将UserDao类型的唯一一个bean赋值给userDao这个成员变量;第二种实现中,Spring会调用 setUserDao方法来将UserDao类型的唯一一个bean装配到userDao这个属性。

1.3. 让@Autowired工作起来
要使@Autowired能够工作,还需要在配置文件中加入以下代码

?spring注脚



1.4. @Qualifier
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出 BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。
1. 可能存在多个UserDao实例

?spring注脚?spring注脚?spring注脚?spring注脚


<context:annotationconfig />将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、 CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及 RequiredAnnotationBeanPostProcessor这4个BeanPostProcessor。

2. 使用Spring注解完成Bean的定义
以上我们介绍了通过@Autowired或@Resource来实现在Bean中自动注入的功能,下面我们将介绍如何注解Bean,从而从XML 配置文件中完全移除Bean定义的配置。

2.1. @Component(不推荐使用)、@Repository、@Service、@Controller
只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:

?spring注脚?spring注脚


这里,所有通过<bean>元素定义Bean的配置内容已经被移除,仅需要添加一行<context:component- scan />配置就解决所有问题了——Spring XML配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan />的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
<context:component-scan />还允许定义过滤器将基包下的某些类纳入或排除。Spring支持以下4种类型的过滤方式:

过滤器类型 表达式范例 说明 注解 org.example.SomeAnnotation 将所有使用SomeAnnotation注解的类过滤出来 类名指定 org.example.SomeClass 过滤指定的类 正则表达式 com\.kedacom\.spring\.annotation\.web\..* 通过正则表达式过滤一些类 AspectJ表达式 org.example..*Service+ 通过AspectJ表达式过滤一些类


以正则表达式为例,我列举一个应用实例:

?spring注脚


值得注意的是<context:component-scan />配置项不但启用了对类包进行扫描以实施注释驱动Bean定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),因此当使用<context:component-scan />后,就可以将<context:annotation-config />移除了。

2.3. 使用@Scope来定义Bean的作用范围
在使用XML定义Bean时,我们可能还需要通过bean的scope属性来定义一个Bean的作用范围,我们同样可以通过@Scope注解来完成这项工作:

?spring注脚@Scope("session")@Component()public class UserSessionBean implements Serializable {...}



3. 参考
http://kingtai168.iteye.com/blog/244002
http://www.iteye.com/topic/244153
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classpath-scanning

读书人网 >软件架构设计

热点推荐