使用限定符微调基于注解的自动装配
@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"/> [id="CO1-1"]1
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier value="action"/> [id="CO1-2"]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 名称进行选择,不需要在注入点使用 |
作为按名称注入的替代方案,请考虑 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
-
public class MovieRecommender { @Autowired @Offline [id="CO2-1"][id="CO1-1"][id="CO1-1"](1) private MovieCatalog offlineCatalog; // ... }
<1> 此行添加 `@Offline` 注解。
- Kotlin
-
class MovieRecommender { @Autowired @Offline [id="CO3-1"][id="CO1-2"][id="CO2-1"](1) private lateinit var offlineCatalog: MovieCatalog // ... }
<1> 此行添加 `@Offline` 注解。
现在 bean 定义只需要一个限定符 type
,如以下示例所示:
<bean class="example.SimpleMovieCatalog">
<qualifier type="Offline"/> [id="CO4-1"]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>