Spring文档2.9

2.9 Annotation-based Container Configuration 基于注解的容器配置

Are annotations better than XML for configuring Spring?

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. The short answer is “it depends.” The long answer is that each approach has its pros and cons, and, usually, it is up to the developer to decide which strategy suits them better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control.

No matter the choice, Spring can accommodate both styles and even mix them together. It is worth pointing out that through its JavaConfig option, Spring lets annotations be used in a non-invasive way, without touching the target components source code and that, in terms of tooling, all configuration styles are supported by the Spring Tools for Eclipse.

基于注释的配置的引入提出了一个问题,即这种方法是否比XML“更好”。简而言之,答案是“视情况而定”。长篇大论的回答是,每种方法都有其优点和缺点,通常由开发人员决定哪种策略更适合他们。由于它们的定义方式,注释在其声明中提供了大量上下文,从而使配置更短、更简洁。然而,XML擅长在不接触源代码或不重新编译它们的情况下连接组件。一些开发人员喜欢将连接放在接近源的地方,而另一些人则认为带注释的类不再是pojo,而且配置变得分散,更难控制。

无论选择什么,Spring都可以同时容纳两种风格,甚至将它们混合在一起。值得指出的是,通过它的JavaConfig选项,Spring允许以一种非侵入性的方式使用注释,而不涉及目标组件源代码,并且,在工具方面,所有的配置风格都得到了Eclipse的Spring工具的支持。

An alternative to XML setup is provided by annotation-based configuration, which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. As mentioned in Example: The RequiredAnnotationBeanPostProcessor, using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IoC container. For example, Spring 2.0 introduced the possibility of enforcing required properties with the @Required annotation. Spring 2.5 made it possible to follow that same general approach to drive Spring’s dependency injection. Essentially, the @Autowired annotation provides the same capabilities as described in Autowiring Collaborators but with more fine-grained control and wider applicability. Spring 2.5 also added support for JSR-250 annotations, such as @PostConstruct and @PreDestroy. Spring 3.0 added support for JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject package such as @Inject and @Named. Details about those annotations can be found in the relevant section.

XML设置的另一种替代方法是基于注释的配置,它依赖于将组件连接起来的字节码元数据,而不是尖括号声明。开发人员不使用XML来描述bean连接,而是通过使用相关类、方法或字段声明上的注释将配置移动到组件类本身。如示例中所述:RequiredAnnotationBeanPostProcessor,将BeanPostProcessor与注释结合使用是扩展Spring IoC容器的一种常见方法。例如,Spring 2.0引入了使用@Required注释强制执行所需属性的可能性。Spring 2.5使得采用相同的通用方法来驱动Spring的依赖项注入成为可能。本质上,@Autowired注解提供了与Autowiring合作者描述的相同的功能,但是更细粒度的控制和更广泛的适用性。Spring 2.5还增加了对JSR-250注释的支持,比如@PostConstruct和@PreDestroy。Spring 3.0增加了对javax中包含的JSR-330 (Java依赖注入)注释的支持。注入包,如@Inject和@Named。有关这些注释的详细信息可以在相关部分找到。

Annotation injection is performed before XML injection. Thus, the XML configuration overrides the annotations for properties wired through both approaches.

注释注入在XML注入之前执行。因此,XML配置覆盖了通过这两种方法连接的属性的配置。

As always, you can register them as individual bean definitions, but they can also be implicitly registered by including the following tag in an XML-based Spring configuration (notice the inclusion of the context namespace):

与往常一样,您可以将它们注册为单独的bean定义,但是也可以通过在基于xml的Spring配置中包含以下标记来隐式注册它们(请注意上下文名称空间的包含):


<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/>

beans>

(The implicitly registered post-processors include AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, and the aforementioned RequiredAnnotationBeanPostProcessor.)

(隐式注册的后处理器包括AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor和前面提到的RequiredAnnotationBeanPostProcessor。)

  • only looks for annotations on beans in the same application context in which it is defined. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Autowired beans in your controllers, and not your services. See The DispatcherServlet for more information.

  • context:annotation-config/只在定义它的应用程序上下文中查找bean上的注释。这意味着,如果你把context:annotation-config/放在一个DispatcherServlet的WebApplicationContext中,它只会检查你的控制器中的@Autowired bean,而不会检查你的服务。有关更多信息,请参见DispatcherServlet。

2.9.1. @Required

The @Required annotation applies to bean property setter methods, as in the following example:

public class SimpleMovieLister {
     

    private MovieFinder movieFinder;

    @Required
    public void setMovieFinder(MovieFinder movieFinder) {
     
        this.movieFinder = movieFinder;
    }

    // ...
}

This annotation indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws an exception if the affected bean property has not been populated. This allows for eager and explicit failure, avoiding NullPointerException instances or the like later on. We still recommend that you put assertions into the bean class itself (for example, into an init method). Doing so enforces those required references and values even when you use the class outside of a container.

该注释指出,必须在配置时通过bean定义中的显式属性值或通过自动装配填充受影响的bean属性。如果未填充受影响的bean属性,容器将抛出异常。这允许立即执行和显式失败,避免了以后出现NullPointerException实例或类似的情况。我们仍然建议将断言放入bean类本身(例如,放入init方法)。即使在容器外部使用类,这样做也会加强那些必需的引用和值。

  • The @Required annotation is formally deprecated as of Spring Framework 5.1, in favor of using constructor injection for required settings (or a custom implementation of InitializingBean.afterPropertiesSet() along with bean property setter methods).

  • 从Spring Framework 5.1开始,@Required注释被正式弃用,支持为所需的设置使用构造函数注入(或InitializingBean.afterPropertiesSet()的自定义实现以及bean属性设置器方法)。

2.9.2 Using @Autowired

  • JSR 330’s @Inject annotation can be used in place of Spring’s @Autowired annotation in the examples included in this section. See here for more details.

  • 在本节包含的示例中,JSR 330的@Inject注释可以代替Spring的@Autowired注释。详情请看这里。

You can apply the @Autowired annotation to constructors, as the following example shows:

public class MovieRecommender {
     

    private final CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
     
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...
}
  • As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean defines only one constructor to begin with. However, if several constructors are available, at least one must be annotated with @Autowired in order to instruct the container which one to use.
  • 从Spring Framework 4.3开始,如果目标bean只定义一个构造函数,那么就不再需要在这样的构造函数上使用@Autowired注解。但是,如果有多个构造函数可用,那么必须至少有一个用@Autowired来注释,以便指示容器使用哪个构造函数。

You can also apply the @Autowired annotation to traditional setter methods, as the following example shows:

您还可以将@Autowired注解应用到传统的setter方法中,如下例所示:

public class SimpleMovieLister {
     

    private MovieFinder movieFinder;

    @Autowired
    public void setMovieFinder(MovieFinder movieFinder) {
     
        this.movieFinder = movieFinder;
    }

    // ...
}

You can also apply the annotation to methods with arbitrary names and multiple arguments, as the following example shows:

您还可以将该注释应用于具有任意名称和多个参数的方法,如下面的示例所示:

public class MovieRecommender {
     

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public void prepare(MovieCatalog movieCatalog,
            CustomerPreferenceDao customerPreferenceDao) {
     
        this.movieCatalog = movieCatalog;
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...
}

You can apply @Autowired to fields as well and even mix it with constructors, as the following example shows:

你也可以将@Autowired应用到字段中,甚至可以和构造函数混合使用,如下面的例子所示:

public class MovieRecommender {
     

    private final CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    private MovieCatalog movieCatalog;

    @Autowired
    public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
     
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...
}

Make sure that your target components (for example, MovieCatalog or CustomerPreferenceDao) are consistently declared by the type that you use for your @Autowired-annotated injection points. Otherwise, injection may fail due to a “no type match found” error at runtime.For XML-defined beans or component classes found via classpath scanning, the container usually knows the concrete type up front. However, for @Bean factory methods, you need to make sure that the declared return type is sufficiently expressive. For components that implement several interfaces or for components potentially referred to by their implementation type, consider declaring the most specific return type on your factory method (at least as specific as required by the injection points referring to your bean).

确保您的目标组件(例如MovieCatalog或CustomerPreferenceDao)是由用于@ autowire注释的注入点的类型一致声明的。否则,注入可能会由于运行时错误“没有找到类型匹配”而失败。

对于通过类路径扫描找到的xml定义的bean或组件类,容器通常预先知道具体的类型。但是,对于@Bean工厂方法,您需要确保声明的返回类型具有足够的表达能力。对于实现多个接口的组件或可能由其实现类型引用的组件,请考虑在工厂方法上声明最特定的返回类型(至少与引用bean的注入点所需的返回类型一样具体)。

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:

您还可以指示Spring通过向需要该类型数组的字段或方法添加@Autowired注释来从ApplicationContext中提供特定类型的所有bean,如下例所示:

public class MovieRecommender {
     

    @Autowired
    private MovieCatalog[] movieCatalogs;

    // ...
}

The same applies for typed collections, as the following example shows:

类型化集合也是如此,如下例所示:

public class MovieRecommender {
     

    private Set<MovieCatalog> movieCatalogs;

    @Autowired
    public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
     
        this.movieCatalogs = movieCatalogs;
    }

    // ...
}

Your target beans can implement the org.springframework.core.Ordered interface or use the @Order or standard @Priority annotation if you want items in the array or list to be sorted in a specific order. Otherwise, their order follows the registration order of the corresponding target bean definitions in the container.

You can declare the @Order annotation at the target class level and on @Bean methods, potentially for individual bean definitions (in case of multiple definitions that use the same bean class). @Order values may influence priorities at injection points, but be aware that they do not influence singleton startup order, which is an orthogonal concern determined by dependency relationships and @DependsOn declarations.

Note that the standard javax.annotation.Priority annotation is not available at the @Bean level, since it cannot be declared on methods. Its semantics can be modeled through @Order values in combination with @Primary on a single bean for each type.

您的目标bean可以实现org.springframe .core。如果希望数组或列表中的项按特定顺序排序,可以使用@Order或标准的@Priority注释。否则,它们的顺序将遵循容器中相应的目标bean定义的注册顺序。

您可以在目标类级别和@Bean方法上声明@Order注释,可能是针对单个bean定义(如果多个定义使用相同的bean类)。@Order值可能会影响注入点的优先级,但是要注意它们不会影响单例启动顺序,这是一个由依赖关系和@DependsOn声明决定的正交关系。

注意,标准的javax.annotation。在@Bean级别上不能使用Priority注释,因为它不能在方法上声明。它的语义可以通过@Order值与针对每种类型的单个bean上的@Primary组合来建模。

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:

即使是类型化的Map实例,只要期望的键类型是String,也可以自动生成。映射值包含预期类型的所有bean,键包含相应的bean名称,如下例所示:

public class MovieRecommender {
     

    private Map<String, MovieCatalog> movieCatalogs;

    @Autowired
    public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
     
        this.movieCatalogs = movieCatalogs;
    }

    // ...
}

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.

默认情况下,当给定注入点没有匹配的候选bean可用时,自动装配将失败。对于声明的数组、集合或映射,至少需要一个匹配的元素。

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):

默认行为是将带注释的方法和字段视为指示所需的依赖项。您可以改变这个行为,如下面的例子所示,使框架能够跳过一个不可满足的注入点,通过标记它为非必需的(例如,,通过设置@Autowired中的required属性为false):

public class SimpleMovieLister {
     

    private MovieFinder movieFinder;

    @Autowired(required = false)
    public void setMovieFinder(MovieFinder movieFinder) {
     
        this.movieFinder = movieFinder;
    }

    // ...
}

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 case, leaving its default value in place.

如果一个非必需的方法的依赖项(或者它的一个依赖项,在有多个参数的情况下)不可用,那么这个方法将不会被调用。在这种情况下,完全不会填充非必需字段,而是保留其默认值。

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.

注入构造函数和工厂方法参数是一种特殊情况,因为@Autowired中的required属性有一些不同的含义,因为Spring的构造函数解析算法可能会处理多个构造函数。默认情况下,构造函数和工厂方法参数是有效需要的,但是在单一构造函数场景中有一些特殊的规则,例如,如果没有匹配的bean可用,则多元素注入点(数组、集合、映射)解析为空实例。这就允许了一种通用的实现模式,在这种模式中,所有依赖项都可以在一个唯一的多参数构造函数中声明——例如,在没有@Autowired注解的情况下声明为一个公共构造函数。

Only one constructor of any given bean class may declare @Autowired with the required attribute set to true, indicating the constructor to autowire when used as a Spring bean. Furthermore, if the required attribute is set to true, only a single constructor may be annotated with @Autowired. If multiple non-required constructors declare the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a primary/default constructor (if present) will be used. If a class only declares a single constructor to begin with, it will always be used, even if not annotated. An annotated constructor does not have to be public.

The required attribute of @Autowired is recommended over the deprecated @Required annotation on setter methods. Setting the required attribute to false indicates that the property is not required for autowiring purposes, and the property is ignored if it cannot be autowired. @Required, on the other hand, is stronger in that it enforces the property to be set by any means supported by the container, and if no value is defined, a corresponding exception is raised.

任何给定bean类只有一个构造函数可以声明@Autowired,并将required属性设置为true,这表明构造函数在用作Spring bean时是自动装配的。此外,如果required属性被设置为true,那么只有一个构造函数可能被@Autowired注解。如果多个非必需的构造函数声明了注释,那么它们将被视为自动装配的候选对象。将选择具有最多依赖项的构造函数,这些依赖项可以通过匹配Spring容器中的bean来满足。如果没有一个候选者可以满足,那么将使用主/默认构造函数(如果存在)。如果一个类一开始只声明一个构造函数,那么它总是会被使用,即使没有注释。带注释的构造函数不一定是公共的。

在setter方法上,建议使用@Autowired的required属性,而不建议使用@Required注释。将required属性设置为false表示该属性对于自动装配目的不是必需的,如果不能自动装配,则忽略该属性。另一方面,@Required更强大,因为它强制通过容器支持的任何方法来设置属性,如果没有定义值,就会引发相应的异常。

Alternatively, you can express the non-required nature of a particular dependency through Java 8’s java.util.Optional, as the following example shows:

或者,您可以通过Java 8的Java .util来表示特定依赖项的非必需性质。可选,如下例所示:

public class SimpleMovieLister {
     

    @Autowired
    public void setMovieFinder(Optional<MovieFinder> movieFinder) {
     
        ...
    }
}

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 builtin null-safety support:

从Spring Framework 5.0开始,您还可以使用@Nullable注释(任何包中的任何类型的注释——例如,javax.annotation.Nullable从JSR-305)或只是利用Kotlin内置的空安全支持:

public class SimpleMovieLister {
     

    @Autowired
    public void setMovieFinder(@Nullable MovieFinder movieFinder) {
     
        ...
    }
}

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:

您还可以将@Autowired用于那些众所周知的可解析依赖项:BeanFactory、ApplicationContext、Environment、ResourceLoader、ApplicationEventPublisher和MessageSource。这些接口及其扩展接口(如ConfigurableApplicationContext或ResourcePatternResolver)将自动解析,不需要特殊的设置。下面的例子自动连线一个ApplicationContext对象:

public class MovieRecommender {
     

    @Autowired
    private ApplicationContext context;

    public MovieRecommender() {
     
    }

    // ...
}
  • The @Autowired, @Inject, @Value, and @Resource annotations are handled by Spring BeanPostProcessor implementations. This means that you cannot apply these annotations within your own BeanPostProcessor or BeanFactoryPostProcessor types (if any). These types must be ‘wired up’ explicitly by using XML or a Spring @Bean method.
  • @Autowired、@Inject、@Value和@Resource注释由Spring BeanPostProcessor实现处理。这意味着您不能在自己的BeanPostProcessor或BeanFactoryPostProcessor类型(如果有的话)中应用这些注释。必须使用XML或Spring @Bean方法显式地“连接”这些类型。

2.9.3 Fine-tuning Annotation-based Autowiring with @Primary使用@Primary微调基于注释的自动装配

Because autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring’s @Primary annotation. @Primary indicates that a particular bean should be given preference when multiple beans are candidates to be autowired to a single-valued dependency. If exactly one primary bean exists among the candidates, it becomes the autowired value.

由于按类型自动装配可能会产生多个候选对象,因此通常需要对选择过程有更多的控制。实现此目的的一种方法是使用Spring的@Primary注释。@Primary表示,当多个bean是要自动生成单值依赖项的候选bean时,应该优先考虑特定的bean。如果在候选bean中只存在一个主bean,那么它就成为autowired值。

Consider the following configuration that defines firstMovieCatalog as the primary MovieCatalog:

考虑一下下面的配置,它将firstMovieCatalog定义为主MovieCatalog:

@Configuration
public class MovieConfiguration {
     

    @Bean
    @Primary
    public MovieCatalog firstMovieCatalog() {
      ... }

    @Bean
    public MovieCatalog secondMovieCatalog() {
      ... }

    // ...
}

With the preceding configuration, the following MovieRecommender is autowired with the firstMovieCatalog:

在前面的配置中,下面的MovieRecommender是用firstMovieCatalog自动生成的:

public class MovieRecommender {
     

    @Autowired
    private MovieCatalog movieCatalog;

    // ...
}

The corresponding bean definitions follow:

相应的bean定义如下:


<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">
        
    bean>

    <bean class="example.SimpleMovieCatalog">
        
    bean>

    <bean id="movieRecommender" class="example.MovieRecommender"/>

beans>

2.9.4 Fine-tuning Annotation-based Autowiring with Qualifiers 使用限定符微调基于注释的自动装配

@Primary is an effective way to use autowiring by type with several instances when one primary candidate can be determined. When you need more control over the selection process, you can use Spring’s @Qualifier annotation. You can associate qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value, as shown in the following example:

@Primary是一种根据类型使用自动装配的有效方法,它可以在多个实例中确定一个主要候选对象。当您需要对选择过程有更多的控制时,您可以使用Spring的@Qualifier注释。您可以将限定符值与特定的参数关联起来,缩小类型匹配集,以便为每个参数选择特定的bean。在最简单的情况下,这可以是一个简单的描述性值,如下面的例子所示:

public class MovieRecommender {
     

    @Autowired
    @Qualifier("main")
    private MovieCatalog movieCatalog;

    // ...
}

You can also specify the @Qualifier annotation on individual constructor arguments or method parameters, as shown in the following example:

您还可以在单个构造函数参数或方法参数上指定@Qualifier注释,如下例所示:

public class MovieRecommender {
     

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public void prepare(@Qualifier("main") MovieCatalog movieCatalog,
            CustomerPreferenceDao customerPreferenceDao) {
     
        this.movieCatalog = movieCatalog;
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...
}

The following example shows corresponding bean definitions.

下面的示例显示了相应的bean定义。


<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"/> 

        
    bean>

    <bean class="example.SimpleMovieCatalog">
        <qualifier value="action"/> 

        
    bean>

    <bean id="movieRecommender" class="example.MovieRecommender"/>

beans>

For a fallback match, the bean name is considered a default qualifier value. Thus, you can define the bean with an id of main instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches. They do not semantically express a reference to a unique bean id. Good qualifier values are main or EMEA or persistent, expressing characteristics of a specific component that are independent from the bean id, which may be auto-generated in case of an anonymous bean definition such as the one in the preceding example.

对于回退匹配,bean名称被认为是默认的限定符值。因此,您可以使用main的id来定义bean,而不是使用嵌套的qualifier元素,从而得到相同的匹配结果。然而,尽管您可以使用这个约定来通过名称引用特定的bean,但是@Autowired基本上是关于带有可选语义限定符的类型驱动注入的。这意味着限定符值,即使使用了bean名称回退,在类型匹配集内也总是具有收缩语义。它们在语义上不表示对惟一bean id的引用。好的限定符值是main或EMEA或persistent,它们表示独立于bean id的特定组件的特征,对于匿名bean定义(如前面示例中的定义),可以自动生成这些特征。

Qualifiers also apply to typed collections, as discussed earlier — for example, to Set. In this case, all matching beans, according to the declared qualifiers, are injected as a collection. This implies that qualifiers do not have to be unique. Rather, they constitute filtering criteria. For example, you can define multiple MovieCatalog beans with the same qualifier value “action”, all of which are injected into a Set annotated with @Qualifier("action").

正如前面所讨论的,限定符也适用于类型化集合—例如,设置。在这种情况下,根据声明的限定符,所有匹配的bean都作为一个集合注入。这意味着限定符不必是唯一的。相反,它们构成了过滤标准。例如,您可以使用相同的限定符值“action”定义多个MovieCatalog bean,所有这些都被注入到一个使用@Qualifier(“action”)注释的集合。

Letting qualifier values select against target bean names, within the type-matching candidates, does not require a @Qualifier annotation at the injection point. If there is no other resolution indicator (such as a qualifier or a primary marker), for a non-unique dependency situation, Spring matches the injection point name (that is, the field name or parameter name) against the target bean names and choose the same-named candidate, if any.

在类型匹配的候选对象中,让qualifier值对目标bean名进行选择,不需要在注入点使用@Qualifier注释。如果没有其他解析指示器(例如限定词或主标记),对于非唯一依赖情况,Spring将针对目标bean名称匹配注入点名称(即字段名称或参数名称),并选择同名的候选项(如果有的话)。

That said, if you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if it is capable of selecting by bean name among type-matching candidates. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process. @Autowired has rather different semantics: After selecting candidate beans by type, the specified String qualifier value is considered within those type-selected candidates only (for example, matching an account qualifier against beans marked with the same qualifier label).

也就是说,如果您打算通过名称来表示注释驱动的注入,那么不要主要使用@Autowired,即使它能够通过bean名称在类型匹配的候选项中进行选择。相反,使用JSR-250 @Resource注释,它的语义定义是通过特定的名称来标识特定的目标组件,声明的类型与匹配过程无关。@Autowired具有相当不同的语义:在根据类型选择候选bean之后,指定的字符串限定符值只在那些类型选择的候选者中被考虑(例如,将一个帐户限定符与标记有相同限定符标签的bean相匹配)。

For beans that are themselves defined as a collection, Map, or array type, @Resource is a fine solution, referring to the specific collection or array bean by unique name. That said, as of 4.3, collection, you can match Map, and array types through Spring’s @Autowired type matching algorithm as well, as long as the element type information is preserved in @Bean return type signatures or collection inheritance hierarchies. In this case, you can use qualifier values to select among same-typed collections, as outlined in the previous paragraph.

对于本身定义为集合、映射或数组类型的bean, @Resource是一个很好的解决方案,它通过惟一名称引用特定的集合或数组bean。也就是说,从4.3开始,收集,您可以通过Spring的@Autowired类型匹配算法来匹配映射和数组类型,只要元素类型信息保存在@Bean返回类型签名或收集继承层次结构中。在这种情况下,可以使用限定符值在相同类型的集合中进行选择,如前一段所述。

As of 4.3, @Autowired also considers self references for injection (that is, references back to the bean that is currently injected). Note that self injection is a fallback. Regular dependencies on other components always have precedence. In that sense, self references do not participate in regular candidate selection and are therefore in particular never primary. On the contrary, they always end up as lowest precedence. In practice, you should use self references as a last resort only (for example, for calling other methods on the same instance through the bean’s transactional proxy). Consider factoring out the effected methods to a separate delegate bean in such a scenario. Alternatively, you can use @Resource, which may obtain a proxy back to the current bean by its unique name.

在4.3中,@Autowired还考虑了注入的自引用(也就是说,回当前注入的bean的引用)。注意,自注入是一种退路。对其他组件的常规依赖始终具有优先级。从这个意义上说,自我推荐不参与常规的候选人选择,因此尤其不属于初选。相反,它们的优先级总是最低的。在实践中,应该只将self引用作为最后的手段(例如,通过bean的事务代理调用同一实例上的其他方法)。在这种情况下,考虑将受影响的方法分解到一个单独的委托bean中。或者,您可以使用@Resource,它可以通过惟一的名称将代理获取到当前bean。

Trying to inject the results from @Bean methods on the same configuration class is effectively a self-reference scenario as well. Either lazily resolve such references in the method signature where it is actually needed (as opposed to an autowired field in the configuration class) or declare the affected @Bean methods as static, decoupling them from the containing configuration class instance and its lifecycle. Otherwise, such beans are only considered in the fallback phase, with matching beans on other configuration classes selected as primary candidates instead (if available).

尝试将来自@Bean方法的结果注入到相同的配置类中也是一种有效的自引用场景。要么在方法签名中实际需要的地方(与configuration类中的autowired字段相反)惰性地解析这些引用,要么将受影响的@Bean方法声明为静态的,将它们与包含它们的configuration类实例及其生命周期解耦。否则,只在回退阶段考虑这些bean,而选择其他配置类上的匹配bean作为主要候选(如果可用)。

@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. In contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, you should stick with qualifiers if your injection target is a constructor or a multi-argument method.

@Autowired适用于字段、构造函数和多参数方法,允许在参数级别通过限定符注释来缩小范围。相反,@Resource只支持带有单个参数的字段和bean属性setter方法。因此,如果您的注入目标是一个构造函数或一个多参数方法,那么您应该坚持使用限定符。

You can create your own custom qualifier annotations. To do so, define an annotation and provide the @Qualifier annotation within your definition, as the following example shows:

您可以创建自己的自定义限定符注释。为此,定义一个注释并在定义中提供@Qualifier注释,如下面的示例所示:

@Target({
     ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Genre {
     

    String value();
}

Then you can provide the custom qualifier on autowired fields and parameters, as the following example shows:

然后你可以在自动装配的字段和参数上提供自定义限定符,如下面的例子所示:

public class MovieRecommender {
     

    @Autowired
    @Genre("Action")
    private MovieCatalog actionCatalog;

    private MovieCatalog comedyCatalog;

    @Autowired
    public void setComedyCatalog(@Genre("Comedy") MovieCatalog comedyCatalog) {
     
        this.comedyCatalog = comedyCatalog;
    }

    // ...
}

Next, you can provide the information for the candidate bean definitions. You can add tags as sub-elements of the tag and then specify the type and value to match your custom qualifier annotations. The type is matched against the fully-qualified class name of the annotation. Alternately, as a convenience if no risk of conflicting names exists, you can use the short class name. The following example demonstrates both approaches:

接下来,您可以提供候选bean定义的信息。您可以添加标记作为标记的子元素,然后指定类型和值来匹配您的自定义qualifier注释。类型与注释的完全限定类名匹配。另外,为了方便起见,如果不存在名称冲突的风险,您可以使用简短的类名。下面的例子演示了这两种方法:


<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"/>
        
    bean>

    <bean class="example.SimpleMovieCatalog">
        <qualifier type="example.Genre" value="Comedy"/>
        
    bean>

    <bean id="movieRecommender" class="example.MovieRecommender"/>

beans>

In Classpath Scanning and Managed Components, you can see an annotation-based alternative to providing the qualifier metadata in XML. Specifically, see Providing Qualifier Metadata with Annotations.

在类路径扫描和托管组件中,您可以看到一个基于注释的替代方法,它可以在XML中提供限定符元数据。具体地说,请参阅使用注释提供限定符元数据。

In some cases, using an annotation without a value may suffice. This can be useful when the annotation serves a more generic purpose and can be applied across several different types of dependencies. For example, you may provide an offline catalog that can be searched when no Internet connection is available. First, define the simple annotation, as the following example shows:

在某些情况下,使用没有值的注释可能就足够了。当注释服务于更一般的用途,并且可以跨多个不同类型的依赖项应用时,这可能很有用。例如,您可以提供一个离线目录,当没有可用的Internet连接时,可以搜索该目录。首先,定义简单的注释,如下例所示:

@Target({
     ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Offline {
     

}

Then add the annotation to the field or property to be autowired, as shown in the following example:

然后将注释添加到要自动装配的字段或属性中,如下例所示:

public class MovieRecommender {
     

    @Autowired
    @Offline 
    private MovieCatalog offlineCatalog;

    // ...
}

Now the bean definition only needs a qualifier type, as shown in the following example:

现在bean定义只需要一个限定符类型,如下面的例子所示:

<bean class="example.SimpleMovieCatalog">
    <qualifier type="Offline"/> 
    
bean>

You can also define custom qualifier annotations that accept named attributes in addition to or instead of the simple value attribute. If multiple attribute values are then specified on a field or parameter to be autowired, a bean definition must match all such attribute values to be considered an autowire candidate. As an example, consider the following annotation definition:

您还可以定义自定义限定符注释,除简单值属性外,它还接受命名属性。如果在要自动装配的字段或参数上指定了多个属性值,则bean定义必须匹配所有这些属性值,才能被视为自动装配候选。以下面的注释定义为例:

@Target({
     ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MovieQualifier {
     

    String genre();

    Format format();
}

In this case Format is an enum, defined as follows:

在这种情况下,格式是enum,定义如下:

public enum Format {
     
    VHS, DVD, BLURAY
}

The fields to be autowired are annotated with the custom qualifier and include values for both attributes: genre and format, as the following example shows:

要自动生成的字段使用自定义限定符进行注释,并包含两个属性的值:类型和格式,如下面的示例所示:

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;

    // ...
}

Finally, the bean definitions should contain matching qualifier values. This example also demonstrates that you can use bean meta attributes instead of the elements. If available, the element and its attributes take precedence, but the autowiring mechanism falls back on the values provided within the `` tags if no such qualifier is present, as in the last two bean definitions in the following example:

最后,bean定义应该包含匹配的限定符值。这个例子还演示了您可以使用bean元属性来代替元素。如果有的话,元素和它的属性是优先的,但是自动装配机制会返回到标签中提供的值,如果没有这样的限定符的话,就像下面例子中的最后两个bean定义一样:


<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>
        
    bean>

    <bean class="example.SimpleMovieCatalog">
        <qualifier type="MovieQualifier">
            <attribute key="format" value="VHS"/>
            <attribute key="genre" value="Comedy"/>
        qualifier>
        
    bean>

    <bean class="example.SimpleMovieCatalog">
        <meta key="format" value="DVD"/>
        <meta key="genre" value="Action"/>
        
    bean>

    <bean class="example.SimpleMovieCatalog">
        <meta key="format" value="BLURAY"/>
        <meta key="genre" value="Comedy"/>
        
    bean>

beans>

2.9.5 Using Generics as Autowiring Qualifiers使用泛型作为自动装配限定符

In addition to the @Qualifier annotation, you can use Java generic types as an implicit form of qualification. For example, suppose you have the following configuration:

除了@Qualifier注释之外,您还可以使用Java泛型类型作为一种隐式的限定形式。例如,假设你有以下配置:

@Configuration
public class MyConfiguration {
     

    @Bean
    public StringStore stringStore() {
     
        return new StringStore();
    }

    @Bean
    public IntegerStore integerStore() {
     
        return new IntegerStore();
    }
}

Assuming that the preceding beans implement a generic interface, (that is, Store and Store), you can @Autowire the Store interface and the generic is used as a qualifier, as the following example shows:

假设前面的bean实现了一个泛型接口(即存储和存储),您可以@Autowire存储接口并将泛型用作限定词,如下面的示例所示:

@Autowired
private Store<String> s1; //  qualifier, injects the stringStore bean

@Autowired
private Store<Integer> s2; //  qualifier, injects the integerStore bean

Generic qualifiers also apply when autowiring lists, Map instances and arrays. The following example autowires a generic List:

通用限定符也适用于自动装配列表、映射实例和数组。下面的例子自动装配一个通用列表:

// Inject all Store beans as long as they have an  generic
// Store beans will not appear in this list
@Autowired
private List<Store<Integer>> s;

2.9.6 Using CustomAutowireConfigurer

CustomAutowireConfigurer is a BeanFactoryPostProcessor that lets you register your own custom qualifier annotation types, even if they are not annotated with Spring’s @Qualifier annotation. The following example shows how to use CustomAutowireConfigurer:

customautowirefigurer是一个BeanFactoryPostProcessor,它允许您注册自己的自定义限定符注释类型,即使它们没有使用Spring的@Qualifier注释。下面的例子展示了如何使用customautowirefigurer:

<bean id="customAutowireConfigurer"
        class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
    <property name="customQualifierTypes">
        <set>
            <value>example.CustomQualifiervalue>
        set>
    property>
bean>

The AutowireCandidateResolver determines autowire candidates by:

  • The autowire-candidate value of each bean definition
  • Any default-autowire-candidates patterns available on the element
  • The presence of @Qualifier annotations and any custom annotations registered with the CustomAutowireConfigurer

AutowireCandidateResolver通过以下方式确定autowire候选对象:

  • 每个bean定义的autowire-candidate值
  • 元素上可用的任何default-autowire-candidate模式
  • @Qualifier注释的存在,以及在customautowirefigurer中注册的任何自定义注释

When multiple beans qualify as autowire candidates, the determination of a “primary” is as follows: If exactly one bean definition among the candidates has a primary attribute set to true, it is selected.

当多个bean符合自动装配候选时,“主bean”的确定如下:如果候选bean中的一个bean定义的主属性设置为true,则选择它。

2.9.7 Injection with @Resource

Spring also supports injection by using the JSR-250 @Resource annotation (javax.annotation.Resource) on fields or bean property setter methods. This is a common pattern in Java EE: for example, in JSF-managed beans and JAX-WS endpoints. Spring supports this pattern for Spring-managed objects as well.

Spring还通过在字段或bean属性设置器方法上使用JSR-250 @Resource注释(javax.annotation.Resource)来支持注入。这是Java EE中的一种常见模式:例如,在jsf管理的bean和JAX-WS端点中。Spring也支持Spring管理对象的这种模式。

@Resource takes a name attribute. By default, Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics, as demonstrated in the following example:

@Resource接受name属性。默认情况下,Spring将该值解释为要注入的bean名。换句话说,它遵循姓名语义,如下例所示:

public class SimpleMovieLister {
     

    private MovieFinder movieFinder;

    @Resource(name="myMovieFinder") 
    public void setMovieFinder(MovieFinder movieFinder) {
     
        this.movieFinder = movieFinder;
    }
}

If no name is explicitly specified, the default name is derived from the field name or setter method. In case of a field, it takes the field name. In case of a setter method, it takes the bean property name. The following example is going to have the bean named movieFinder injected into its setter method:

如果没有显式指定名称,则默认名称派生自字段名或setter方法。对于字段,它采用字段名。对于setter方法,它采用bean属性名。下面的例子将把名为movieFinder的bean注入到它的setter方法中:

public class SimpleMovieLister {
     

    private MovieFinder movieFinder;

    @Resource
    public void setMovieFinder(MovieFinder movieFinder) {
     
        this.movieFinder = movieFinder;
    }
}

The name provided with the annotation is resolved as a bean name by the ApplicationContext of which the CommonAnnotationBeanPostProcessor is aware. The names can be resolved through JNDI if you configure Spring’s SimpleJndiBeanFactory explicitly. However, we recommend that you rely on the default behavior and use Spring’s JNDI lookup capabilities to preserve the level of indirection.

注释提供的名称由CommonAnnotationBeanPostProcessor所感知的ApplicationContext解析为bean名称。如果您显式地配置Spring的SimpleJndiBeanFactory,则可以通过JNDI解析这些名称。但是,我们建议您依赖缺省行为并使用Spring的JNDI查找功能来保持间接级别。

In the exclusive case of @Resource usage with no explicit name specified, and similar to @Autowired, @Resource finds a primary type match instead of a specific named bean and resolves well known resolvable dependencies: the BeanFactory, ApplicationContext, ResourceLoader, ApplicationEventPublisher, and MessageSource interfaces.

在没有指定显式名称且类似于@Autowired的@Resource使用情况下,@Resource会找到一个主类型匹配项,而不是一个特定的已命名bean,并解决众所周知的可解析依赖项:BeanFactory、ApplicationContext、ResourceLoader、ApplicationEventPublisher和MessageSource接口。

Thus, in the following example, the customerPreferenceDao field first looks for a bean named “customerPreferenceDao” and then falls back to a primary type match for the type CustomerPreferenceDao:

因此,在下面的示例中,customerPreferenceDao字段首先查找名为“customerPreferenceDao”的bean,然后返回到customerPreferenceDao类型的主类型匹配:

public class MovieRecommender {
     

    @Resource
    private CustomerPreferenceDao customerPreferenceDao;

    @Resource
    private ApplicationContext context; 

    public MovieRecommender() {
     
    }

    // ...
}

2.9.8 Using @Value

@Value is typically used to inject externalized properties:

@Value通常用于注入外化属性:

@Component
public class MovieRecommender {
     

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name}") String catalog) {
     
        this.catalog = catalog;
    }
}

With the following configuration:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
      }

And the following application.properties file:

catalog.name=MovieCatalog

In that case, the catalog parameter and field will be equal to the MovieCatalog value.

在这种情况下,catalog参数和字段将等于MovieCatalog值。

A default lenient embedded value resolver is provided by Spring. It will try to resolve the property value and if it cannot be resolved, the property name (for example ${catalog.name}) will be injected as the value. If you want to maintain strict control over nonexistent values, you should declare a PropertySourcesPlaceholderConfigurer bean, as the following example shows:

Spring提供了一个默认的宽松嵌入式值解析器。它将尝试解析属性值,如果不能解析,属性名(例如${catalog.name})将作为值注入。如果你想对不存在的值保持严格的控制,你应该声明一个PropertySourcesPlaceholderConfigurer bean,如下面的例子所示:

@Configuration
public class AppConfig {
     

     @Bean
     public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
     
           return new PropertySourcesPlaceholderConfigurer();
     }
}

When configuring a PropertySourcesPlaceholderConfigurer using JavaConfig, the @Bean method must be static.

使用JavaConfig配置PropertySourcesPlaceholderConfigurer时,@Bean方法必须是静态的。

Using the above configuration ensures Spring initialization failure if any ${} placeholder could not be resolved. It is also possible to use methods like setPlaceholderPrefix, setPlaceholderSuffix, or setValueSeparator to customize placeholders.

如果无法解析任何${}占位符,则使用上述配置可确保Spring初始化失败。也可以使用setPlaceholderPrefix、setPlaceholderSuffix或setValueSeparator等方法来定制占位符。

Spring Boot configures by default a PropertySourcesPlaceholderConfigurer bean that will get properties from application.properties and application.yml files.

默认情况下,SpringBoot配置一个PropertySourcesPlaceholderConfigurer bean,它将从应用程序获取属性。属性和应用程序。yml文件。

Built-in converter support provided by Spring allows simple type conversion (to Integer or int for example) to be automatically handled. Multiple comma-separated values can be automatically converted to String array without extra effort.

Spring提供的内置转换器支持允许自动处理简单的类型转换(例如,转换为整数或int)。多个逗号分隔的值可以自动转换为字符串数组,而不需要额外的工作。

It is possible to provide a default value as following:

可以提供一个默认值如下:

@Component
public class MovieRecommender {
     

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name:defaultCatalog}") String catalog) {
     
        this.catalog = catalog;
    }
}

A Spring BeanPostProcessor uses a ConversionService behind the scene to handle the process for converting the String value in @Value to the target type. If you want to provide conversion support for your own custom type, you can provide your own ConversionService bean instance as the following example shows:

Spring BeanPostProcessor在后台使用一个ConversionService来处理将@Value中的字符串值转换为目标类型的过程。如果你想为自己的自定义类型提供转换支持,你可以提供自己的ConversionService bean实例,如下例所示

@Configuration
public class AppConfig {
     

    @Bean
    public ConversionService conversionService() {
     
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        conversionService.addConverter(new MyCustomConverter());
        return conversionService;
    }
}

When @Value contains a SpEL expression the value will be dynamically computed at runtime as the following example shows:

当@Value包含SpEL表达式时,该值将在运行时动态计算,如下例所示:

@Component
public class MovieRecommender {
     

    private final String catalog;

    public MovieRecommender(@Value("#{systemProperties['user.catalog'] + 'Catalog' }") String catalog) {
     
        this.catalog = catalog;
    }
}

SpEL also enables the use of more complex data structures:

SpEL还支持使用更复杂的数据结构:

@Component
public class MovieRecommender {
     

    private final Map<String, Integer> countOfMoviesPerCatalog;

    public MovieRecommender(
            @Value("#{
     {'Thriller': 100, 'Comedy': 300}}") Map<String, Integer> countOfMoviesPerCatalog) {
     
        this.countOfMoviesPerCatalog = countOfMoviesPerCatalog;
    }
}

2.9.9 Using @PostConstruct and @PreDestroy

The CommonAnnotationBeanPostProcessor not only recognizes the @Resource annotation but also the JSR-250 lifecycle annotations: javax.annotation.PostConstruct and javax.annotation.PreDestroy. Introduced in Spring 2.5, the support for these annotations offers an alternative to the lifecycle callback mechanism described in initialization callbacks and destruction callbacks. Provided that the CommonAnnotationBeanPostProcessor is registered within the Spring ApplicationContext, a method carrying one of these annotations is invoked at the same point in the lifecycle as the corresponding Spring lifecycle interface method or explicitly declared callback method. In the following example, the cache is pre-populated upon initialization and cleared upon destruction:

CommonAnnotationBeanPostProcessor不仅可以识别@Resource注释,还可以识别JSR-250生命周期注释:javax.annotation.PostConstruct javax.annotation.PreDestroy。在Spring 2.5中引入了对这些注释的支持,为初始化回调和销毁回调中描述的生命周期回调机制提供了一种替代方法。如果CommonAnnotationBeanPostProcessor是在Spring ApplicationContext中注册的,那么在生命周期的同一点上,就会调用携带这些注释之一的方法,即对应的Spring生命周期接口方法或显式声明的回调方法。在下面的例子中,缓存在初始化时被预填充,在销毁时被清除:

public class CachingMovieLister {
     

    @PostConstruct
    public void populateMovieCache() {
     
        // populates the movie cache upon initialization...
    }

    @PreDestroy
    public void clearMovieCache() {
     
        // clears the movie cache upon destruction...
    }
}

For details about the effects of combining various lifecycle mechanisms, see Combining Lifecycle Mechanisms.

有关组合各种生命周期机制的效果的详细信息,请参阅组合生命周期机制。

  • Like @Resource, the @PostConstruct and @PreDestroy annotation types were a part of the standard Java libraries from JDK 6 to 8. However, the entire javax.annotation package got separated from the core Java modules in JDK 9 and eventually removed in JDK 11. If needed, the javax.annotation-api artifact needs to be obtained via Maven Central now, simply to be added to the application’s classpath like any other library.
  • 与@Resource一样,@PostConstruct和@PreDestroy注释类型也是JDK 6到8的标准Java库的一部分。但是,整个javax。注释包在JDK 9中与核心Java模块分离,最终在JDK 11中被删除。如果需要,可以使用javax。现在需要通过Maven Central获得javax.annotation-api工件,只需将其像其他库一样添加到应用程序的类路径中即可。

2.10 Classpath Scanning and Managed Components

Most examples in this chapter use XML to specify the configuration metadata that produces each BeanDefinition within the Spring container. The previous section (Annotation-based Container Configuration) demonstrates how to provide a lot of the configuration metadata through source-level annotations. Even in those examples, however, the “base” bean definitions are explicitly defined in the XML file, while the annotations drive only the dependency injection. This section describes an option for implicitly detecting the candidate components by scanning the classpath. Candidate components are classes that match against a filter criteria and have a corresponding bean definition registered with the container. This removes the need to use XML to perform bean registration. Instead, you can use annotations (for example, @Component), AspectJ type expressions, or your own custom filter criteria to select which classes have bean definitions registered with the container.

本章的大多数示例使用XML指定配置元数据,这些元数据在Spring容器中生成每个bean定义。上一节(基于注释的容器配置)演示了如何通过源代码级注释提供大量配置元数据。然而,即使在这些示例中,“基础”bean定义也是在XML文件中显式定义的,而注释只驱动依赖项注入。本节描述通过扫描类路径隐式检测候选组件的选项。候选组件是根据筛选条件匹配的类,并且具有注册到容器中的相应bean定义。这样就不需要使用XML来执行bean注册。相反,您可以使用注释(例如,@Component)、AspectJ类型表达式或您自己的自定义筛选条件来选择哪些类具有向容器注册的bean定义。

  • Starting with Spring 3.0, many features provided by the Spring JavaConfig project are part of the core Spring Framework. This allows you to define beans using Java rather than using the traditional XML files. Take a look at the @Configuration, @Bean, @Import, and @DependsOn annotations for examples of how to use these new features.
  • 从Spring 3.0开始,Spring JavaConfig项目提供的许多特性都是Spring核心框架的一部分。这允许您使用Java而不是使用传统的XML文件定义bean。查看@Configuration、@Bean、@Import和@DependsOn注释,了解如何使用这些新特性。

你可能感兴趣的:(Spring-我要学会你,spring)