Spring Boot auto-configuration (auto-configurtion) demystified

In this chapter, we will reveal the operation mechanism of Spring Boot's Auto Configuration (Auto Configuration) for you. When it comes to auto-configuration, the @EnableAutoConfiguration annotation is definitely inseparable.

package org.springframework.boot.autoconfigure;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

   Class<?>[] exclude() default {};
   String[] excludeName() default {};
}

Two meta-annotations are involved here: @AutoConfigurationPackage, @Import(EnableAutoConfigurationImportSelector.class), where @AutoConfigurationPackage is defined as follows:

package org.springframework.boot.autoconfigure;

import ....

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

The @Import meta annotation is used in the @AutoConfigurationPackage annotation definition. The value of the annotation attribute is AutoConfigurationPackages.Registrar.class. The AutoConfigurationPackages.Registrar class implements the interface ImportBeanDefinitionRegistrar

The @Import annotation can accept the following Java classes of defined types

  • Classes annotated with @Configuration
  • ImportSelector implementation class: code to handle @Configuration annotated classes
  • DeferredImportSelector implementation class: Similar to ImportSelector, the difference is that the processing operation is delayed until all other configuration items are processed before proceeding.
  • ImportBeanDefinitionRegistrar implementation class

AutoConfigurationPackages.Registrar will register the bean with the Spring container, and the bean itself will store the list of user-defined configuration packages. Spring Boot itself uses this list. For example: for spring-boot-autoconfigure data access configuration class, you can get this configuration list through the static method: **AutoConfigurationPackages.get(BeanFactory)**, the following is the sample code.

package com.logicbig.example;

import ...

@EnableAutoConfiguration
public class AutoConfigurationPackagesTest {

   public static void main (String[] args) {

       SpringApplication app =
                     new SpringApplication(AutoConfigurationPackagesTest.class);
       app.setBannerMode(Banner.Mode.OFF);
       app.setLogStartupInfo(false);
       ConfigurableApplicationContext c = app.run(args);
       List<String> packages = AutoConfigurationPackages.get(c);
       System.out.println("packages: "+packages);
   }
}

The code output is as follows:

2017-01-03 10:17:37.372  INFO 10752 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Tue Jan 03 10:17:37 CST 2017]; root of context hierarchy
2017-01-03 10:17:38.155  INFO 10752 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
packages: [com.logicbig.example]
2017-01-03 10:17:38.170  INFO 10752 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Tue Jan 03 10:17:37 CST 2017]; root of context hierarchy
2017-01-03 10:17:38.171  INFO 10752 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

**@Import(EnableAutoConfigurationImportSelector.class) annotation is the startup entry of auto-configuration mechanism. EnableAutoConfigurationImportSelector implements the interface DeferredImportSelector, which internally calls the SpringFactoriesLoader.loadFactoryNames()** method, which loads the configuration class from META-INF/spring.factories.

	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
			AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
				getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
		Assert.notEmpty(configurations,
				"No auto configuration classes found in META-INF/spring.factories. If you "
						+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

Find the value of the key org.springframework.boot.autoconfigure.EnableAutoConfiguration from spring.factories:

spring-boot-autoconfigure is implicitly included by default in all starters

One of the following code snippets for the configuration class JmxAutoConfiguration

 package org.springframework.boot.autoconfigure.jmx;

   .......
 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 import org.springframework.boot.autoconfigure.condition.SearchStrategy;
  .....

 @Configuration
 @ConditionalOnClass({ MBeanExporter.class })
 @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true)
 public class JmxAutoConfiguration implements
                                    EnvironmentAware, BeanFactoryAware {
    .....
 }

@ConditionalOnClass

@ConditionalOnClass is an annotation defined by the meta-annotation **@Conditional(OnClassCondition.class**. We know that @Conditional is a conditional annotation. Only when the condition is true, the class and method annotated by @Conditional will be loaded into the Spring component container . For the above example code snippet, only when MBeanExporter.class has been included in the classpath (specifically checking the loading logic similar to Class.forName, when the target class is included in the classpath, the method returns true, otherwise returns false), OnClassCondition #matches() will return true.

@ConditionalOnProperty

Similar to **@ConditionalOnClass , @ConditionalOnProperty is another @Conditional type variable, an annotation defined by the meta-annotation @Conditional(OnPropertyCondition.class)**. **OnPropertyCondition#matches()** will return true only if the target property contains the specified value, or the above code snippet:

  @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled",
                         havingValue = "true", matchIfMissing = true)

If our application is configured with spring.jmx.enabled=true, then the Spring container will automatically register JmxAutoConfiguration, and matchIfMissing=true means that it is true by default (the configuration property is not set).

Some other conditional annotations

Package 'org.springframework.boot.autoconfigure.condition, all conditional annotations follow the ConditionalOnXyz` naming convention. If you want to develop a custom starter package, you need to understand these APIs, and for other developers, it is best to understand the basic operating mechanism.

Use the --debug parameter

@EnableAutoConfiguration
public class DebugModeExample {

  public static void main (String[] args) {
      //just doing this programmatically for demo
      String[] appArgs = {"--debug"};

      SpringApplication app = new SpringApplication(DebugModeExample.class);
      app.setBannerMode(Banner.Mode.OFF);
      app.setLogStartupInfo(false);
      app.run(appArgs);
    }
}

output

2017-01-02 21:15:17.322 DEBUG 5704 --- [           main] o.s.boot.SpringApplication               : Loading source class com.logicbig.example.DebugModeExample
2017-01-02 21:15:17.379 DEBUG 5704 --- [           main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped (empty) config file 'file:/D:/LogicBig/example-projects/spring-boot/boot-customizing-autoconfig/target/classes/application.properties' (classpath:/application.properties)
2017-01-02 21:15:17.379 DEBUG 5704 --- [           main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped (empty) config file 'file:/D:/LogicBig/example-projects/spring-boot/boot-customizing-autoconfig/target/classes/application.properties' (classpath:/application.properties) for profile default
2017-01-02 21:15:17.384  INFO 5704 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f0a87b3: startup date [Mon Jan 02 21:15:17 CST 2017]; root of context hierarchy
2017-01-02 21:15:18.032  INFO 5704 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-01-02 21:15:18.047 DEBUG 5704 --- [           main] utoConfigurationReportLoggingInitializer :


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   GenericCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition)

   JmxAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.jmx.export.MBeanExporter' (OnClassCondition)
      - @ConditionalOnProperty (spring.jmx.enabled=true) matched (OnPropertyCondition)

   JmxAutoConfiguration#mbeanExporter matched:
      - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: current) did not find any beans (OnBeanCondition)

   JmxAutoConfiguration#mbeanServer matched:
      - @ConditionalOnMissingBean (types: javax.management.MBeanServer; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JmxAutoConfiguration#objectNamingStrategy matched:
      - @ConditionalOnMissingBean (types: org.springframework.jmx.export.naming.ObjectNamingStrategy; SearchStrategy: current) did not find any beans (OnBeanCondition)

   NoOpCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched:
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition)

   RedisCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition)

   SimpleCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition)


Negative matches:
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

   AopAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)

   ArtemisAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client

 ...............................
 ....................


Exclusions:
-----------

    None


Unconditional classes:
----------------------

    org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration

    org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration

    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration

    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration



2017-01-02 21:15:18.058  INFO 5704 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f0a87b3: startup date [Mon Jan 02 21:15:17 CST 2017]; root of context hierarchy
2017-01-02 21:15:18.059  INFO 5704 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

in the above output

  • Positive matches: The @Conditional condition is true and the configuration class is loaded by the Spring container.
  • Negative matches: @Conditional condition is false, configuration class is not loaded by Spring container.
  • Exclusions: The application side explicitly excludes the loading configuration
  • Unconditional classes: Auto-configured classes do not contain any class-level conditions, that is, classes are always loaded automatically.

Disable auto-configuration for specific classes

@EnableAutoConfiguration(exclude = {JmxAutoConfiguration.class})
public class ExcludeConfigExample {

    public static void main (String[] args) {
         //just doing this programmatically for demo
         String[] appArgs = {"--debug"};

        SpringApplication app = new SpringApplication(ExcludeConfigExample.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.setLogStartupInfo(false);
        app.run(appArgs);
    }
}

output


  .............

=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   GenericCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition)

   NoOpCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched:
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition)

   RedisCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition)

   SimpleCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition)


Negative matches:
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

   AopAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)


  .................................

Exclusions:
-----------

    org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration


Unconditional classes:
----------------------

    org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration

    org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration

    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration

    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324069539&siteId=291194637