Spring - 基于注解的配置
从 Spring 2.5 开始,可以使用 注解 来配置依赖注入。这样就不必使用 XML 来描述 bean 的布线,而是可以将 bean 配置移到组件类本身,通过在相关 class、method 或 field 声明上使用注解。
注解注入在 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 自动将值布线到属性、方法和构造函数中。让我们来看看几个重要的注解,了解它们的工作原理 −
| 序号 | 注解 & 描述 |
|---|---|
| 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 注解。 |