文章参考来源:Spring Framework官方文档
本文讲述的注解有:@Required,@Autowired,@Primary,@Qualifier,@Resource,@Value,@PostConstruct 和@PreDestroy
注解注入在XML注入之前执行。因此,XML配置覆盖了通过两种方法连接的属性的注释。
- 对于注解 <context:annotation-config/ > 相当于注册了以下几个后处理器post-processors:
- ConfigurationClassPostProcessor
- AutowiredAnnotationBeanPostProcessor
- CommonAnnotationBeanPostProcessor
- PersistenceAnnotationBeanPostProcessor
- EventListenerMethodProcessor
- 关于@Required注解,@Required注解应用于bean属性setter方法。在Spring 5.1正式弃用,官方建议对必需的设置使用构造函数注入(或自定义的org.springframework.beans.factory.InitializingBean实现)
package org.springframework.beans.factory.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a method (typically a JavaBean setter method) as being 'required': that is,
* the setter method must be configured to be dependency-injected with a value.
*
* <p>Please do consult the javadoc for the {@link RequiredAnnotationBeanPostProcessor}
* class (which, by default, checks for the presence of this annotation).
*
* @author Rob Harrop
* @since 2.0
* @see RequiredAnnotationBeanPostProcessor
* @deprecated as of 5.1, in favor of using constructor injection for required settings
* (or a custom {@link org.springframework.beans.factory.InitializingBean} implementation)
*/
@Deprecated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Required {
}
- 关于注解@Autowired,JSR 330 @Inject注解可以实现Spring @Autowired的相同效果。(JSR 330 是Java 的依赖注入标准)。@Autowired、@Inject、@Value和@Resource注解是由Spring BeanPostProcessor实现处理的。这意味着不能在自己的BeanPostProcessor或BeanFactoryPostProcessor类型(如果有的话)中应用这些注释。这些类型必须通过使用XML或Spring @Bean方法显式地“连接”起来。
- 关于自动装配中的微调注解——@Primary。如果自动装配含有多个“候选”bean,且想在候选bean中选定一个主bean,即优先考虑某个特定bean,那么可以将@Primary纳入使用。下面的例子中,MovieRecommender自动装配时将优先选择被 @Primary修饰的firstMovieCatalog/带有primary="true"的。
@Configuration
public class MovieConfiguration {
@Bean
@Primary
public MovieCatalog firstMovieCatalog() { ... }
@Bean
public MovieCatalog secondMovieCatalog() { ... }
// ...
}
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="example.SimpleMovieCatalog" primary="true">
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
</beans>
- 关于自动装配中的微调注解——@Qualifier。
默认情况下,@Autowired 按类型装配 Spring Bean。如果容器中有多个相同类型的 bean,则框架将抛出 NoUniqueBeanDefinitionException, 以提示有多个满足条件的 bean 进行自动装配。程序无法正确做出判断使用哪一个在。
使用@Autowire自动注入的时候,加上@Qualifier(“test”)可以明确指定注入哪个对象。
//我们定义了两个TestClass对象,分别是testClass1和testClass2
//我们如果在另外一个对象中直接使用@Autowire去注入的话,spring肯定不知道使用哪个对象
//会排除异常 required a single bean, but 2 were found
@Configuration
public class TestConfiguration {
@Bean("testClass1")
TestClass testClass1(){
return new TestClass("TestClass1");
}
@Bean("testClass2")
TestClass testClass2(){
return new TestClass("TestClass2");
}
}
@RestController
public class TestController {
//此时这两个注解的连用就类似 @Resource(name="testClass1")
@Autowired
@Qualifier("testClass1")
private TestClass testClass;
@GetMapping("/test")
public Object test(){
return testClassList;
}
}
- 关于注解@Resource。在字段或bean属性注值上,Spring也支持使用JSR-250 @Resource注解(javax.annotation.Resource)。@Resource接受一个name属性。
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Resource(name="myMovieFinder")
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
如果以上@Resource例子中没有指定name属性,那么其name属性默认为:movieFinder(字段名)
public class MovieRecommender {
@Resource
private CustomerPreferenceDao customerPreferenceDao;
@Resource
private ApplicationContext context;
public MovieRecommender() {
}
// ...
}
在没有明确指定名称的情况下,@Resource会先按照默认名称去寻找,然后按照类型去匹配寻找。而@Autowired默认按照类型。比如以上例子中,首先查找名为“customerPreferenceDao”的bean,然后返回找寻与customerPreferenceDao类型匹配的主类型CustomerPreferenceDao 。
- 关于注解@Value。@Value通常用于注入外部化属性。比如以下:
@Component
public class MovieRecommender {
private final String catalog;
public MovieRecommender(@Value("${catalog.name}") String catalog) {
this.catalog = catalog;
}
}
需要增加configuration:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig { }
以及application.properties文件:
catalog.name=MovieCatalog
Spring提供了一个默认的、宽松的嵌入式值解析器。当遇到一个不能解析的值,Spring首先会尝试解析属性值,尝试无果后属性名(例如${catalog.name})将作为值注入。如果希望严格控制不存在的值,则应该声明PropertySourcesPlaceholderConfigurer bean,如下例所示:
@Configuration
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
需注意的是:使用Java配置PropertySourcesPlaceholderConfigurer时,@Bean方法必须是static。
在使用PropertySourcesPlaceholderConfigurer进行上述配置后,若${}无法解析到值,Spring初始化会失败。也可以使用setPlaceholderPrefix、setPlaceholderSuffix或setvalueseseparator等方法来定制占位符。
对于 Spring Boot来说,默认配置的PropertySourcesPlaceholderConfigurer ,将会去application.properties 和application.yml中寻值。
- 关于注解@PostConstruct 和@PreDestroy。CommonAnnotationBeanPostProcessor不仅可以识别@Resource注释,还可以识别JSR-250生命周期注释:javax.annotation.PostConstruct和javax.annotation.PreDestroy。在Spring 2.5中引入的对这些注释的支持提供了一种替代初始化回调和销毁回调中描述的生命周期回调机制的方法,即@PostConstruct和@PreDestroy可以做到InitializingBean 和DisposableBean的效果。
public class CachingMovieLister {
//初始化实例设值后调用:等同于InitializingBean.afterPropertiesSet()
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
//容器销毁前调用:等同于DisposableBean的destroy()
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
与@Resource一样,@PostConstruct和@PreDestroy注解一直是JDK 6到8的标准Java库的一部分。然而,整个javax.annotation包在JDK 9中与核心Java模块分离,并最终在JDK 11中被删除。如果想使用javax.annotation-api,需要通过Maven Central获得,只需像其他库一样添加到应用程序的类路径中。