Spring基于注解配置

从Spring2.5开始就有可能使用注释来配置依赖注入。而是采用XML来描述一个bean接线,你可以使用注解的相关类,方法或字段声明将bean配置到组件类本身。

注释注入在XML注入之前进行,因此后者的配置将覆盖前者通过两种方式连接的属性。

注释接线默认情况下不开启在Spring容器。所以,我们才可以使用基于注解的接线,我们将需要启用它在我们的Spring配置文件。因此,考虑到已在下列情况下,配置文件要使用的任何注释在Spring应用程序。

<?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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>

当<context:annotation-config/>配置后,您就可以开始注释代码表明,Spring自动连线的值到属性,方法和构造函数。让我们来看看几个重要的注解,以了解它们是如何工作的:

S.N. 注释与说明
1 @Required
@Required注释适用于bean属性的setter方法​​。
2 @Autowired
@Autowired 注释可以应用到bean属性的setter方法​​,非setter方法​​,构造函数和属性。
3 @Qualifier
@ Autowired随着@ Qualifier注释可以用来通过指定确切的bean将有线,除去混乱。
4 JSR-250 Annotations
Spring支持JSR-250的基础的注解,其中包括了@Resource,@PostConstruct和@PreDestroy注解。