Spring 简明教程
Spring - Annotation Based Configuration
从 Spring 2.5 开始,可以使用 annotations 配置依赖注入成为可能。因此,与其使用 XML 来描述 Bean 装配,你可以使用对相关类、方法或字段声明的注释将 Bean 配置移到组件类本身中。
Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
注释注入在 XML 注入前执行。因此,对于通过两种方法连接的属性,后一种配置将覆盖前一种配置。
Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches.
在 Spring 容器中,注释装配不会默认启用。因此,在使用基于注释的装配之前,我们需要在 Spring 配置文件中启用它。所以如果你想在你的 Spring 应用程序中使用任何注释,请考虑以下配置文件。
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application.
<?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 应自动将值连接到属性、方法和构造函数中。让我们来看一些重要的注释以了解它们如何工作:-
Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us look at a few important annotations to understand how they work −
Sr.No. |
Annotation & Description |
1 |
@RequiredThe @Required annotation applies to bean property setter methods. |
2 |
@AutowiredThe @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties. |
3 |
@QualifierThe @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired. |
4 |
JSR-250 AnnotationsSpring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations. |