Using @Autowired
可以在本节中包含的示例中使用 JSR 330 的 JSR 330’s |
可以将`@Autowired`注释应用于构造函数,如下例所示:
You can apply the @Autowired
annotation to constructors, as the following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
class MovieRecommender @Autowired constructor(
private val customerPreferenceDao: CustomerPreferenceDao)
自 Spring Framework 4.3 起,如果目标 Bean 本身仅定义了一个构造函数,就不再需要在该构造函数上使用 "@32" 注解。但是,如果有多个构造函数可用,并且没有主/默认构造函数,那么为了指示容器使用哪个构造函数,必须至少有一个构造函数用 "@33" 注解。请参阅 "@34" 上的讨论内容,了解详细信息。 As of Spring Framework 4.3, an |
还可以将`@Autowired`注释应用于_传统_setter 方法,如下例所示:
You can also apply the @Autowired
annotation to traditional setter methods,
as the following example shows:
-
Java
-
Kotlin
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
class SimpleMovieLister {
@set:Autowired
lateinit var movieFinder: MovieFinder
// ...
}
还可以将注释应用于名称任意且具有多个参数的方法,如下例所示:
You can also apply the annotation to methods with arbitrary names and multiple arguments, as the following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(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(movieCatalog: MovieCatalog,
customerPreferenceDao: CustomerPreferenceDao) {
this.movieCatalog = movieCatalog
this.customerPreferenceDao = customerPreferenceDao
}
// ...
}
还可以将`@Autowired`应用于字段,甚至可以将它与构造函数混合使用,如下例所示:
You can apply @Autowired
to fields as well and even mix it with constructors, as the
following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
private MovieCatalog movieCatalog;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
class MovieRecommender @Autowired constructor(
private val customerPreferenceDao: CustomerPreferenceDao) {
@Autowired
private lateinit var movieCatalog: MovieCatalog
// ...
}
确保目标组件(例如 Make sure that your target components (for example, 对于通过类路径扫描找到的 XML 定义的 Bean 或组件类,容器在前面通常已知具体类型。然而,对于 For XML-defined beans or component classes found via classpath scanning, the container
usually knows the concrete type up front. However, for |
自 4.3 起, As of 4.3, |
你还可以指示 Spring 从 ApplicationContext
提供特定类型的全部 Bean,方法是将 @Autowired
注解添加到期待该类型数组的字段或方法,如下例所示:
You can also instruct Spring to provide all beans of a particular type from the
ApplicationContext
by adding the @Autowired
annotation to a field or method that
expects an array of that type, as the following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
private MovieCatalog[] movieCatalogs;
// ...
}
class MovieRecommender {
@Autowired
private lateinit var movieCatalogs: Array<MovieCatalog>
// ...
}
对于类型化的集合,遵循同样原则,如下例所示:
The same applies for typed collections, as the following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
@Autowired
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
class MovieRecommender {
@Autowired
lateinit var movieCatalogs: Set<MovieCatalog>
// ...
}
如果要以特定顺序对数组或列表中的项目进行排序,那么你的目标 Bean 可以实现 Your target beans can implement the 你可以在目标类级别和 You can declare the 请注意,配置类上的 Note that 请注意,标准 Note that the standard |
只要期望的键类型为 String
,那么即使是类型化的 Map
实例也可以自动注入。地图值包含所有期望类型的 Bean,而键包含对应的 Bean 名称,如下例所示:
Even typed Map
instances can be autowired as long as the expected key type is String
.
The map values contain all beans of the expected type, and the keys contain the
corresponding bean names, as the following example shows:
-
Java
-
Kotlin
public class MovieRecommender {
private Map<String, MovieCatalog> movieCatalogs;
@Autowired
public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
class MovieRecommender {
@Autowired
lateinit var movieCatalogs: Map<String, MovieCatalog>
// ...
}
默认情况下,当没有可以匹配特定注入点的候选 Bean 可用时,自动注入会失败。如果声明了数组、集合或地图,则至少应有一个匹配元素。
By default, autowiring fails when no matching candidate beans are available for a given injection point. In the case of a declared array, collection, or map, at least one matching element is expected.
默认行为是将带注释的方法和字段视为指示必需的依赖。你可以更改此行为,如下例所示,允许框架通过将其标记为非必需(即,将 @Autowired
中的 required
属性设置为 false
)来跳过一个无法满足的注入点:
The default behavior is to treat annotated methods and fields as indicating required
dependencies. You can change this behavior as demonstrated in the following example,
enabling the framework to skip a non-satisfiable injection point through marking it as
non-required (i.e., by setting the required
attribute in @Autowired
to false
):
-
Java
-
Kotlin
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired(required = false)
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
class SimpleMovieLister {
@Autowired(required = false)
var movieFinder: MovieFinder? = null
// ...
}
如果其依赖(或多个参数的情况中的其一个依赖)不可用,那么一个非必需方法根本不会被调用。在此类情况下,一个非必需字段根本不会被填充,从而让其默认值保留在原位。 A non-required method will not be called at all if its dependency (or one of its dependencies, in case of multiple arguments) is not available. A non-required field will not get populated at all in such cases, leaving its default value in place. 换句话说,将 In other words, setting the |
注入的构造函数和工厂方法参数是一种特殊情况,因为 @Autowired
中的 required
属性具有稍有不同的含义,这是由于 Spring 的可能处理多个构造函数的构造函数解决算法。在单构造函数场景中,构造函数和工厂方法参数实际上默认必需,但有几个特殊规则,例如如果没有可匹配 Bean,那么多元素注入点(数组、集合、地图)解析为空实例。这允许通用实现模式,在该模式中,所有依赖都可以声明在唯一的带多个参数的构造函数中——例如,声明为未带 @Autowired
注解的单个公共构造函数。
Injected constructor and factory method arguments are a special case since the required
attribute in @Autowired
has a somewhat different meaning due to Spring’s constructor
resolution algorithm that may potentially deal with multiple constructors. Constructor
and factory method arguments are effectively required by default but with a few special
rules in a single-constructor scenario, such as multi-element injection points (arrays,
collections, maps) resolving to empty instances if no matching beans are available. This
allows for a common implementation pattern where all dependencies can be declared in a
unique multi-argument constructor — for example, declared as a single public constructor
without an @Autowired
annotation.
只能在一个给定 Bean 类的构造函数中使用 Only one constructor of any given bean class may declare |
或者,你可以通过 Java 8 的 java.util.Optional
表达特定依赖的非必需性质,如下例所示:
Alternatively, you can express the non-required nature of a particular dependency
through Java 8’s java.util.Optional
, as the following example shows:
public class SimpleMovieLister {
@Autowired
public void setMovieFinder(Optional<MovieFinder> movieFinder) {
...
}
}
从 Spring Framework 5.0 起,你还可以使用 @Nullable
注解(任何包中的任何种类的注解——例如 JSR-305 中的 javax.annotation.Nullable
)或只是利用 Kotlin 内置的空安全性支持:
As of Spring Framework 5.0, you can also use a @Nullable
annotation (of any kind
in any package — for example, javax.annotation.Nullable
from JSR-305) or just leverage
Kotlin built-in null-safety support:
-
Java
-
Kotlin
public class SimpleMovieLister {
@Autowired
public void setMovieFinder(@Nullable MovieFinder movieFinder) {
...
}
}
class SimpleMovieLister {
@Autowired
var movieFinder: MovieFinder? = null
// ...
}
你还可以将 @Autowired
用于众所周知并且可以解析的依赖:BeanFactory
、ApplicationContext
、Environment
、ResourceLoader
、ApplicationEventPublisher
和 MessageSource
。这些接口及其扩展接口(例如 ConfigurableApplicationContext
或 ResourcePatternResolver
)会被自动解析,而不需要任何特殊设置。以下示例自动注入 ApplicationContext
对象:
You can also use @Autowired
for interfaces that are well-known resolvable
dependencies: BeanFactory
, ApplicationContext
, Environment
, ResourceLoader
,
ApplicationEventPublisher
, and MessageSource
. These interfaces and their extended
interfaces, such as ConfigurableApplicationContext
or ResourcePatternResolver
, are
automatically resolved, with no special setup necessary. The following example autowires
an ApplicationContext
object:
-
Java
-
Kotlin
public class MovieRecommender {
@Autowired
private ApplicationContext context;
public MovieRecommender() {
}
// ...
}
class MovieRecommender {
@Autowired
lateinit var context: ApplicationContext
// ...
}
The |