Bean's Advanced Assembly

Configuration profile bean

For different environments need to configure different bean, Spring provides solutions that bean profile function. First of all the different bean definition to one or more profile, and then to determine which bean is created based on the activation of the profile.

@Profile annotation specifies which profile belongs to a bean, the profile is activated only when the bean can be created.

@Profile be used at the class level, it can also be used at the method level.

The bean can define different environments in a configuration class using @Profile ( "") to specify its profile, indicate that the bean is created only when the corresponding profile is activated.

As can be configured in the XML configuration file.

No statement in any bean will always create a profile of, and activating it does not matter which profile.

Activation profile

Spring in determining the activation of the profile, relies on two properties: spring.profiles.active and spring.profiles.default.

If the active property is set, its value is used to determine which profile is activated

If no active, Spring will look for the default value to determine which profile is activated

If no active and default settings, Spring will create a profile of the bean is not defined

Arrangement of two properties:

  • As the initialization parameter DispatcherServlet
  • As the application context parameter Wen
  • As JNDI entries
  • As an environment variable
  • As the JVM system properties
  • Based on the integration testing, using settings @ActiveProfiles

Conditioned bean

@Conditional annotation is used to configure the condition of the bean, the method can be used with @Bean, if the given condition evaluates to true, it will create the bean, otherwise ignore this bean.

@Bean
@Conditional(MagicExistsCondition.class)
public MagicBean magicBean() {
    return new MagicBean();
}

Ambiguity automatic assembly process

As long as a bean match the desired result, it is effective automated assembly.

If a bean is not only capable of matching results, then this will hinder ambiguity Spring automatic assembly properties, structural parameters or process parameters.

With a preferred identity bean

Use @Primary annotation which an optional set of bean preferred, and @Component can be used in combination, can be used in combination @Bean, told Spring in the face of ambiguity to select bean.

Bean defined autowiring

Use @Qualifier comment

 

Guess you like

Origin www.cnblogs.com/minguo/p/10964263.html