几个重要的 Spring 注解

<context:annotation-config />
Spring 容器默认禁止注解装配。所以,在使用基于注解的自动装配前,我们需要在 Spring 配置中启用它。最简单的启用方式是使用 Spring 的 context 命名空间配置中的 <context:annotation-config /> 元素。<context:annotation-config /> 告诉 Spring 我们打算使用基于注解的自动装配。一旦配置完成,我们就可以对代码添加注解,标识 Spring 应该为属性、方法和构造器进行自动装配。

<context:component-scan base-package="com.wjxie" />
<context:annotation-config /> 有助于消除 Spring 配置中的 <property> 和 <constructor-arg> 元素,但是我们任然需要使用 <bean> 元素显式定义 Bean 。 <context:component-scan> 不但能够完成与 <context:annotation-config> 一样的工作,还允许 Spring 自动检测 Bean 和定义 Bean 。这意味着不使用 <bean> 元素, Spring 中的大多数(或者所有) Bean 都能够实现定义和装配。 <context:component-scan> 元素会扫描指定包及其子包,并查找出能够自动注册为 Spring Bean 的类。
<context:component-scan> 默认情况下会扫描 @Component, @Controller, @Service, @Repository 所标记的类;但它还可以使用 <context:include-filter> 或者 <context:exclude-filter> ,来扫描或者排除满足某些条件的类。说实话,这种用法不多,大部分还是使用前一种,即基于注解的扫描策略。

<aop:aspectj-autoproxy />
使用 @Aspect 注解标记的 pojo 最终肯定想要被应用为一个切面,遗憾的是它不会自动变成切面(<context:component-scan> 会识别到吗?可能不会!)。你需要在 Spring 上下文中显示声明一个 bean: AnnotationAwareAspectJAutoProxyCreator 。这个类名很长不易记忆,所以 Spring 提供了另外一种方式: <aop:aspectj-autoproxy /> 。总之,它的作用就是启用基于注解的切面。

<tx:annotation-driven transactionManager="txManager"/>
提示 Spring 扫描使用 @Transactional 注解的类或方法。

猜你喜欢

转载自dsxwjhf.iteye.com/blog/2221880
今日推荐