通过限定符优化基于注解的自动装配
当可以确定一个主(或非备用)候选时,@Primary 和 @Fallback 是在使用类型自动装配多个实例的有效方法。
当您需要更多地控制选择过程时,可以使用 Spring 的 @Qualifier 注解。您可以将限定符值与特定的参数关联起来,从而缩小类型匹配的集合,以便为每个参数选择一个特定的 bean。在最简单的情况下,这可以是一个普通的描述性值,如以下示例所示:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
@Qualifier("main")
private MovieCatalog movieCatalog;
// ...
}
class MovieRecommender {
@Autowired
@Qualifier("main")
private lateinit var movieCatalog: MovieCatalog
// ...
}
您还可以将 @Qualifier 注解指定在单个构造函数参数或方法参数上,如以下示例所示:
-
Java
-
Kotlin
public class MovieRecommender {
private final MovieCatalog movieCatalog;
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(@Qualifier("main") MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
class MovieRecommender {
private lateinit var movieCatalog: MovieCatalog
private lateinit var customerPreferenceDao: CustomerPreferenceDao
@Autowired
fun prepare(@Qualifier("main") movieCatalog: MovieCatalog,
customerPreferenceDao: CustomerPreferenceDao) {
this.movieCatalog = movieCatalog
this.customerPreferenceDao = customerPreferenceDao
}
// ...
}
以下示例显示了相应的 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
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">
<qualifier value="main"/> (1)
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier value="action"/> (2)
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
</beans>
| 1 | 带有 main 限定符值的 bean 与带有相同限定符值的构造函数参数进行自动装配。 |
| 2 | 带有 action 限定符值的 bean 与带有相同限定符值的构造函数参数进行自动装配。 |
对于回退匹配,bean 名称被视为默认限定符值。因此,您可以定义 id 为 main 的 bean,而不是使用嵌套的限定符元素,从而产生相同的匹配结果。然而,尽管您可以使用此约定按名称引用特定 bean,但 @Autowired 根本上是带有可选语义限定符的类型驱动注入。这意味着限定符值,即使在 bean 名称回退的情况下,也总是在类型匹配集合中具有缩小语义。它们在语义上不表达对唯一 bean id 的引用。好的限定符值是 main 或 EMEA 或 persistent,它们表达了特定组件的特征,独立于 bean id,在匿名 bean 定义(如前一个示例中的)情况下,bean id 可能是自动生成的。
限定符也适用于类型化集合,如前所述——例如,对于 Set<MovieCatalog>。在这种情况下,所有匹配的 bean,根据声明的限定符,都将作为集合注入。这意味着限定符不必是唯一的。相反,它们构成筛选条件。例如,您可以定义多个具有相同限定符值“action”的 MovieCatalog bean,所有这些 bean 都被注入到用 @Qualifier("action") 注解的 Set<MovieCatalog> 中。
|
在类型匹配候选者中,让限定符值根据目标 bean 名称进行选择,不需要在注入点使用 自 6.1 版本以来,这需要存在 |
作为按名称注入的替代方案,请考虑 JSR-250 的 @Resource 注解,它在语义上定义为通过其唯一名称识别特定目标组件,而声明的类型与匹配过程无关。@Autowired 具有截然不同的语义:在按类型选择候选 bean 之后,指定的 String 限定符值仅在那些类型选定的候选者中考虑(例如,将 account 限定符与标有相同限定符标签的 bean 进行匹配)。
对于本身被定义为集合、Map 或数组类型的 bean,@Resource 是一个很好的解决方案,它通过唯一名称引用特定的集合或数组 bean。也就是说,您也可以通过 Spring 的 @Autowired 类型匹配算法来匹配集合、Map 和数组类型,只要在 @Bean 返回类型签名或集合继承层次结构中保留了元素类型信息。在这种情况下,您可以使用限定符值在相同类型的集合中进行选择,如前一段所述。
@Autowired 也考虑自引用注入(即,引用回当前正在注入的 bean)。详见 自注入。
@Autowired 适用于字段、构造函数和多参数方法,允许通过参数级别的限定符注解进行细化。相比之下,@Resource 仅支持字段和带有单个参数的 bean 属性 setter 方法。因此,如果您的注入目标是构造函数或多参数方法,您应该坚持使用限定符。
您可以创建自己的自定义限定符注解。为此,请定义一个注解并在您的定义中提供 @Qualifier 注解,如以下示例所示:
-
Java
-
Kotlin
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Genre {
String value();
}
@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class Genre(val value: String)
然后,您可以将自定义限定符提供给自动装配的字段和参数,如以下示例所示:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
@Genre("Action")
private MovieCatalog actionCatalog;
private MovieCatalog comedyCatalog;
@Autowired
public void setComedyCatalog(@Genre("Comedy") MovieCatalog comedyCatalog) {
this.comedyCatalog = comedyCatalog;
}
// ...
}
class MovieRecommender {
@Autowired
@Genre("Action")
private lateinit var actionCatalog: MovieCatalog
private lateinit var comedyCatalog: MovieCatalog
@Autowired
fun setComedyCatalog(@Genre("Comedy") comedyCatalog: MovieCatalog) {
this.comedyCatalog = comedyCatalog
}
// ...
}
接下来,您可以为候选 bean 定义提供信息。您可以添加 <qualifier/> 标签作为 <bean/> 标签的子元素,然后指定 type 和 value 来匹配您的自定义限定符注解。类型与注解的完全限定类名进行匹配。或者,为了方便起见,如果不存在名称冲突的风险,您可以使用短类名。以下示例演示了这两种方法:
<?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">
<qualifier type="Genre" value="Action"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier type="example.Genre" value="Comedy"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
</beans>
在 类路径扫描和托管组件 中,您可以看到一种基于注解的替代方法来在 XML 中提供限定符元数据。具体请参阅 使用注解提供限定符元数据。
在某些情况下,不带值的注解可能就足够了。当注解具有更通用的用途并可以应用于几种不同类型的依赖项时,这会很有用。例如,您可能提供一个离线目录,当没有互联网连接时可以进行搜索。首先,定义简单注解,如以下示例所示:
-
Java
-
Kotlin
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Offline {
}
@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class Offline
然后将注解添加到要自动装配的字段或属性中,如以下示例所示:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
@Offline (1)
private MovieCatalog offlineCatalog;
// ...
}
| 1 | 此行添加 @Offline 注解。 |
class MovieRecommender {
@Autowired
@Offline (1)
private lateinit var offlineCatalog: MovieCatalog
// ...
}
| 1 | 此行添加 @Offline 注解。 |
现在 bean 定义只需要一个限定符 type,如以下示例所示:
<bean class="example.SimpleMovieCatalog">
<qualifier type="Offline"/> (1)
<!-- inject any dependencies required by this bean -->
</bean>
| 1 | 此元素指定了限定符。 |
您还可以定义自定义限定符注解,除了简单 value 属性外,还接受命名属性。如果要在自动装配的字段或参数上指定多个属性值,则 bean 定义必须匹配所有此类属性值才能被视为自动装配候选。例如,考虑以下注解定义:
-
Java
-
Kotlin
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MovieQualifier {
String genre();
Format format();
}
@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MovieQualifier(val genre: String, val format: Format)
在这种情况下,Format 是一个枚举,定义如下:
-
Java
-
Kotlin
public enum Format {
VHS, DVD, BLURAY
}
enum class Format {
VHS, DVD, BLURAY
}
要自动装配的字段用自定义限定符注解,并包含 genre 和 format 两个属性的值,如以下示例所示:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
@MovieQualifier(format=Format.VHS, genre="Action")
private MovieCatalog actionVhsCatalog;
@Autowired
@MovieQualifier(format=Format.VHS, genre="Comedy")
private MovieCatalog comedyVhsCatalog;
@Autowired
@MovieQualifier(format=Format.DVD, genre="Action")
private MovieCatalog actionDvdCatalog;
@Autowired
@MovieQualifier(format=Format.BLURAY, genre="Comedy")
private MovieCatalog comedyBluRayCatalog;
// ...
}
class MovieRecommender {
@Autowired
@MovieQualifier(format = Format.VHS, genre = "Action")
private lateinit var actionVhsCatalog: MovieCatalog
@Autowired
@MovieQualifier(format = Format.VHS, genre = "Comedy")
private lateinit var comedyVhsCatalog: MovieCatalog
@Autowired
@MovieQualifier(format = Format.DVD, genre = "Action")
private lateinit var actionDvdCatalog: MovieCatalog
@Autowired
@MovieQualifier(format = Format.BLURAY, genre = "Comedy")
private lateinit var comedyBluRayCatalog: MovieCatalog
// ...
}
最后,bean 定义应包含匹配的限定符值。此示例还演示了您可以使用 bean 元属性而不是 <qualifier/> 元素。如果可用,<qualifier/> 元素及其属性具有优先权,但如果不存在此类限定符,则自动装配机制会回退到 <meta/> 标签中提供的值,如以下示例中的最后两个 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
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">
<qualifier type="MovieQualifier">
<attribute key="format" value="VHS"/>
<attribute key="genre" value="Action"/>
</qualifier>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier type="MovieQualifier">
<attribute key="format" value="VHS"/>
<attribute key="genre" value="Comedy"/>
</qualifier>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<meta key="format" value="DVD"/>
<meta key="genre" value="Action"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<meta key="format" value="BLURAY"/>
<meta key="genre" value="Comedy"/>
<!-- inject any dependencies required by this bean -->
</bean>
</beans>