Annotation @Autoconfiguration

The annotation @AutoConfiguration is used to define an auto-configuration (default configuration) when there is a condition.

[!note]
This is a meta-data annotation, which means it just for descriptive.

Example:

  • JDBC when we haven't configure an database will auto configure a memory database for us

How to create an @AutoConfiguration class:

First we need to create the class.

@Configuration  
@AutoConfiguration  
@ConditionalOnProperty(  
    prefix = "austin.configure",  
    value = "enabled",  
    havingValue = "true",  
    matchIfMissing = false   // default to false if not exist
)  
@Slf4j  
public class MyAutoConfiguration {  
  public MyAutoConfiguration() {  
    log.info("Initialised MyAutoConfiguration");  
  }  
}

In here we define that our class need to based on a property of austin.configure.enabled=true in one of the Spring Property File

Next, we need to create a file in resources/META-INF/spring/ name org.springframework.boot.autoconfigure.AutoConfiguration.imports

with the value to our class

dev.auspham.config.MyAutoConfiguration

That's it, now when we have

austin.configure:  
  enabled: true

In our property, this class will be initialised hence we can see the log. Normally this goes with @ConditionalOnMissingBean or something

For example:

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@AutoConfiguration
// Some conditions ...
public class MyAutoConfiguration {

    // Auto-configured beans ...

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(SomeService.class)
    public static class SomeServiceConfiguration {

        @Bean
        @ConditionalOnMissingBean
        public SomeService someService() {
            return new SomeService();
        }

    }

}