springboot2.0 auto configuration Automatic configuration

concept

The essence of springboot auto configuration is to automatically configure various bean s of spring. Then the application can use the bean directly through injection methods such as @Autowired.
For example, automatically configure redisTemplate, jdbcTemplate and other bean s.

principle

1. Enable @EnableAutoConfiguration annotation

If you write the @SpringBootApplication annotation, you don't need to write @EnableAutoConfiguration. \

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
@SpringCloudApplication = @SpringBootApplication + @EnableDiscoveryClient + @EnableCircuitBreaker

2. After the @EnableAutoConfiguration annotation is enabled, an AutoConfigurationImportSelector class will be automatically introduced

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

    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be
     * applied.
     * @return the class names to exclude
     * @since 1.3.0
     */
    String[] excludeName() default {};

}

It will scan the META-INF/spring.factories files in all jar packages under the classpath

3. spring.factories file

spring.factories file for spring-boot-autoconfigure.jar

 

 

There will be a key of org.springframework.boot.autoconfigure.EnableAutoConfiguration in the spring.factories file

configure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

spring boot will automatically configure all auto-configuration classes under the key of org.springframework.boot.autoconfigure.EnableAutoConfiguration.

You can see that it contains automatic configuration classes for modules such as RabbitMq, MongoDB, Redis, JdbcTemplate, Thymeleaf, WebFlux, WebSocket, etc.

4. Generally, the automatic configuration class has the @Configuration annotation, which is equivalent to a spring xml file, which can configure beans through the @bean annotation.

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}

@ConditionalOnXXX:

  • @ConditionalOnBean (a Bean will only be instantiated if an object exists in the current context
  • @ConditionalOnClass (a Bean will only be instantiated when a class is on the classpath)
  • @ConditionalOnExpression (a Bean will only be instantiated when the expression is true)
  • @ConditionalOnMissingBean (a Bean will only be instantiated if an object does not exist in the current context)
  • @ConditionalOnMissingClass (a Bean will only be instantiated when a class does not exist on the class path)
  • @ConditionalOnProperty(value = “spring.cloud.config.enabled”, matchIfMissing = true) (a Bean will only be instantiated when the value of a configuration is a certain condition)

5. When configuring a bean, it is indispensable to obtain the properties of the properties or yml file

5.1 Map the value of the configuration file to POJO through @ConfigurationProperties(prefix=”xxxx”)

application.yml

test:
  id: 1
  name: test

Any POJO class, for example: Properties.java, the class name is optional, and the prefix of the configuration property is specified by prefix

@ConfigurationProperties(prefix="test")
public class Properties {
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

5.2 Convert the POJO class of the configuration file into a spring bean

5.2.1. Use @EnableConfigurationProperties(Properties.class) where you want to use the configuration to convert it into a spring bean

@RestController
@EnableConfigurationProperties(Properties.class)
public class CommonController extends BaseController {
    //change into spring of bean After that, you can inject and use
    @Autowired
    private Properties properties;

    @RequestMapping(value = "/properties", method = RequestMethod.GET)
    public Properties getProperties() {

        log.info(properties.toString());

        return properties;
    }

}

If you write @EnableConfigurationProperties directly without specifying the Properties class, it must be in the same directory or subdirectory.

5.2.2. Convert it to spring bean through @Bean configuration

@Configuration
public class MyConfiguration {

    @Bean
    public Properties properties() {
        return new Properties();
    }

}

5.2.3. Convert it to spring bean through @Component configuration

@Component
@ConfigurationProperties(prefix="test")
public class Properties {
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

After being converted into a spring bean, you can inject the bean to use it by any injection method where you want to use it.

5.2.4. Summary

When writing the spring boot starter, because all classes are not in the @ComponentScan directory that is started, use 5.2.1 or 5.2.2 to obtain configuration file information.

When writing a specific spring boot application service, the configuration classes are all in the @ComponentScan directory that is started, and it is more convenient to use the method 5.2.3

Original address: https://blog.csdn.net/ifrozen/article/details/79931143

Actual combat -- springboot configuration rocketmq

starters project

1.pom.xml

<dependency>
      <groupId>com.aliyun.openservices</groupId>
      <artifactId>ons-client</artifactId>
      <version>1.8.4.Final</version>
    </dependency>

2.resources->META-INF->spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.bjgxzd.boot.config.MqAutoConfiguration

3.MqAutoConfiguration

@Configuration
@ImportAutoConfiguration(value = {MqConfiguration.class})
public class MqAutoConfiguration {

  @Bean
  public  CommandLineRunner logRunner (){
    return args -> {
      System.out.println("==== GX rocket MQ loaded ====");
    };
  }

}

4.MqConfiguration

@Configuration
@EnableConfigurationProperties({MqProperties.class})
public class MqConfiguration {

  @Autowired
  private MqProperties mqProperties;

  @Bean(initMethod = "start", destroyMethod = "shutdown")
  @ConditionalOnMissingBean(ProducerBean.class)
  public ProducerBean buildProducer() {
    ProducerBean producer = new ProducerBean();
    producer.setProperties(getMqProperties());
    return producer;
  }

  private Properties getMqProperties(){
    Properties properties = new Properties();
    properties.setProperty(PropertyKeyConst.AccessKey, mqProperties.getAccessKey());
    properties.setProperty(PropertyKeyConst.SecretKey, mqProperties.getSecretKey());
    properties.setProperty(PropertyKeyConst.ONSAddr, mqProperties.getOnsAddr());
    return properties;
  }

  @ConditionalOnMissingBean(OrderProducerBean.class)
  @Bean(initMethod = "start", destroyMethod = "shutdown")
  public OrderProducerBean buildOrderProducer() {
    OrderProducerBean orderProducerBean = new OrderProducerBean();
    orderProducerBean.setProperties(getMqProperties());
    return orderProducerBean;
  }

}

5.MqProperties

@Data
@ConfigurationProperties(prefix = "mq.rocketmq")
public class MqProperties {
  private String accessKey;
  private String secretKey;
  private String onsAddr;
}

 

syncsrv project

application.yml

mq:
  rocketmq:
    access-key: 62f49160c57b4f158a8ab3ebd2ff66cc
    secret-key: J8H3v+Go55DIimy6gbKu3Bbnc0U=
    ons-addr: http://172.169.101.121:8080/rocketmq/nsaddr4broker-internal

 

pom.xml

mq Well integrated, directly dependent
<dependency>
  <groupId>com.bjgxzd</groupId>
  <artifactId>gx-mq-spring-boot-starter</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>

 

Startup class QfjsSyncApplication

@SpringBootApplication
public class QfjsSyncApplication implements CommandLineRunner {

  public static void main(String[] args) {
    SpringApplication.run(QfjsSyncApplication.class, args);
  }


  @Override
  public void run(String... args) throws Exception {

  }
}

 

use

You can send a message directly by injecting
private
final ProducerBean producer; public TestController(ProducerBean producer) { this.producer = producer; }

 

Tags: Spring Boot

Posted by jeffshead on Wed, 11 May 2022 21:42:43 +0300