注:由于本人不大习惯注解方式,所以讲解完这里的注解实现基本配置之后,以后就不再单独把注解拿出来讲解了。
五:Spring注解
1.准备工作
(1)导入common-annotations.jar
(2)导入schema文件 文件名为spring-context-2.5.xsd
(3)在xml的beans节点中配置
2.xml配置工作
<?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"
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"
default-default-lazy-init="true">
<!--将针对注解的处理器配置好 -->
<context:annotation-config />
<!-- 使用annotation定义事务-->
<tx:annotation-driventransaction-manager="transactionManager" proxy-target-class="true"/>
<!--使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入base-package为需要扫描的包(含所有子包)-->
<context:component-scanbase-package="com" />
.....
<beans>
注:<context:component-scan base-package="*.*" />
该配置隐式注册了多个对注解进行解析的处理器,如:
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor
其实,注解本身做不了任何事情,和XML一样,只起到配置的作用,主要在于背后强大的处理器,其中就包括了<context:annotation-config/>配置项里面的注解所使用的处理器,所以配置了<context:component-scanbase-package="">之后,便无需再配置<context:annotation-config>
1.在java代码中使用@Autowired或@Resource注解方式进行装配 ,这两个注解的区别是:@Autowired默认按类型装配,@Resource