Spring的Annotation配置方法

        手动配置Spring的bean是一件极为头疼的事情,工作量大不说,还特别容易写错,Annotation标签很好的解决了这个问题,会帮我们剩下很多时间,接下来就是配置的方法:

第一步:添加common-annotations.jar包;
第二步:引入对应的命名空间及对应的Schema文件地址:
<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 /> 让Spring启用对annotation的支持。它其实是注册了多个对annotation进行解析处理的处理器:
  • AutowiredAnnotionBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotionBeanPostProcessor
  • RequiredAnnotationBeanPostProcessor.

第四步:在配置文件中添加需要进行扫描的包路径,例如:<context:component-scan base-package="com.mossad" />就是扫描com.mossad包及其子包下所有的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"
	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 />
	<context:component-scan base-package="com.mossad" />

</beans>

大功告成!接下来就可以使用各种标签进行各种配置了!
                               
记一下@Resource标签和@Autowired标签的区别和用法:
1、@Resource和@Autowired都可以用来标记bean的field属性、成员方法、构造函数、形参的,标记field属性的目的是为field注入相应的bean。
2、@Resource标签默认是byName自动注入,也就是说它会自动注入与field名称相同的bean
	@Resource
	private StockService stockService;
也可以通过设置name属性来指定注入bean的名称,如下所示,此时注入的bean就是abcService而不是stockService了
	@Resource("abcService")
	private StockService stockService;
它还有一个属性是type,用来指定bean的类型,如果不设置,那么Spring会通过反射获取field的类型,然后查找相同类型的bean进行注入,如果多余一个则会抛出异常。
3、@Autowired标签默认是byType自动注入,但是它也可以通过另外一个@Qualifier标签指定bean的name
	@Autowired
	@Qualifier("stockService")
	private StockService stockService;

4、@Resource位于javax.annotation包下,是来自Java EE规范的一个Annotation,Spring直接借鉴了该Annotation来为目标Bean指定协作者Bean;@Autowired是Spring自己的标签,来提供自动装配。
5、设置了这两个标签之后,就都不需要setter方法了。

猜你喜欢

转载自mossad.iteye.com/blog/1520258