Common Annotation Configuration for SpringBoot

Keywords: Java Spring Mybatis Attribute xml

Annotation configuration of SpringBook

Common annotations

@Configuration

From Spring 3.0, @Configuration is used to define configuration classes, which can replace xml configuration files. The annotated classes contain one or more methods annotated by @Bean. These methods will be scanned by Annotation Config Application Context or Annotation Config Web Application Context classes and used to build bean definitions, initially. Spring container.

The configuration class using the @Configuration annotation has the following requirements:

  • Can not be declared as final type;
  • Not an anonymous class;
  • Nested inner classes must be declared static.

@Bean

@ Bean annotations tell Spring that a method with @Bean annotations will return an object that should be registered as a bean in the Spring application context.
@ Bean s are annotations at the method level, mainly used in classes with @Configuration annotations or in classes with @Component annotations.

@EnableConfigurationProperties

@ The Configuration Properties annotation is mainly used to convert properties or yml configuration files into bean s, while the @Enable Configuration Properties annotation is used to validate the @Configuration Properties annotation.
If you configure only the @Configuration Properties annotation, you can't get the bean s transformed by the properties configuration file in the IOC container. Of course, adding @Component to the annotated class of @Configuration Properties can also make it handed over to spring boot management.

@AutoConfigureAfter

@ AutoConfigureAfter(DataSourceAutoConfiguration.class) // / Load the current class after loading the configured class

@PostConstruct

PostConstruct annotations are used on methods that need to be executed after dependency injection is complete to perform any initialization.
Note: This method must not have any parameters; the return type of this method must be void; this method must not throw checked exceptions;

Conditional loading annotations

  • @ ConditionalOnBean(DataSource.class) instantiates a bean when there is a DataSource.class bean
  • @ Conditional On Missing Bean, instantiated when no bean exists
  • @ ConditionalOnClass, a Bean is instantiated only when a class exists
  • @ Conditional OnMissing Class, a Bean is instantiated only when no class exists
  • @ Conditional OnProperty (prefix = syj, name = algorithm, havingValue = counter, matchIfMissing = true) instantiates a class when there is an attribute prefixed with SYJ in the configuration file, the attribute name is algorithm, and its value is token.

meta annotation

Meta-annotations are annotations that can be annotated on other annotations. Here are four basic meta-annotations.

1, @Retention: Define the retention strategy for annotations

    @Retention(RetentionPolicy.SOURCE)   //Annotations exist only in source code and are not included in class bytecode files
    @Retention(RetentionPolicy.CLASS)     // The default retention policy, annotations will exist in the class bytecode file, but cannot be obtained at runtime.
    @Retention(RetentionPolicy.RUNTIME)  // Annotations exist in the class bytecode file and can be retrieved by reflection at run time.

2, @Target: Define the purpose of annotations

@Target(ElementType.TYPE)   //Interfaces, classes, enumerations, annotations
@Target(ElementType.FIELD) //Constants of fields and enumerations
@Target(ElementType.METHOD) //Method
@Target(ElementType.PARAMETER) //Method parameter
@Target(ElementType.CONSTRUCTOR)  //Constructor
@Target(ElementType.LOCAL_VARIABLE)//local variable
@Target(ElementType.ANNOTATION_TYPE)//annotation
@Target(ElementType.PACKAGE) //Package

3, @Document: Explains that the annotation will be included in javadoc

4, @Inherited: Explains that subclasses can inherit the annotation in the parent class

Comprehensive use (take mybatis as an example)

1. Declare a Configuration configuration class

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)  //Load the current class after loading the configured class
public class MybatisAutoConfiguration {

  private static final Logger logger = LoggerFactory.getLogger(MybatisAutoConfiguration.class);

  private final MybatisProperties properties;

  private final Interceptor[] interceptors;

  private final ResourceLoader resourceLoader;

  private final DatabaseIdProvider databaseIdProvider;

  private final List<ConfigurationCustomizer> configurationCustomizers;

  //Beans that have been instantiated in parameters are automatically injected
  public MybatisAutoConfiguration(MybatisProperties properties,
                                  ObjectProvider<Interceptor[]> interceptorsProvider,
                                  ResourceLoader resourceLoader,
                                  ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                  ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {
    this.properties = properties;
    this.interceptors = interceptorsProvider.getIfAvailable();
    this.resourceLoader = resourceLoader;
    this.databaseIdProvider = databaseIdProvider.getIfAvailable();
    this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
  }

  @PostConstruct  //Execute this method after the configuration is loaded
  public void checkConfigFileExists() {
    //Check whether configLocation of the configuration is loaded into the resource
    if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
      Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
      Assert.state(resource.exists(), "Cannot find config location: " + resource
          + " (please add config file or check your Mybatis configuration)");
    }
  }

  @Bean
  @Primary  //When spring instantiates multiple DataSource bean s, this is injected by default when automatic injection occurs.
  @ConfigurationProperties(prefix = "spring.datasource.druid.oracle")
  public DataSource dataSource() {
      return DruidDataSourceBuilder.create().build();
  }

  //Use injection-specific bean s with @Qualifier
  @Bean(name="transactionManager")  //** declares the bean name returned, defaulting to the method name tmOracle**
  DataSourceTransactionManager tmOracle(@Qualifier("dataSource") DataSource dataSource) {  
      DataSourceTransactionManager tm = new DataSourceTransactionManager(dataSource);
      return tm;
  }

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    //The following omits the initialization operation of sqlSessionFactory
  }

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    //...
  }

II. Configuration file information is loaded into the Properties class

@ConfigurationProperties(prefix = "mybatis")
public class MybatisProperties {

  private String configLocation;  //Corresponding configuration mybatis.configLocation=
  
  ...
  //set and get methods
}

Use of custom annotations

Posted by noimad1 on Wed, 11 Sep 2019 00:37:59 -0700