Springboot principle of automatic configuration

Source: Internet
Author: User

First, the Operation principle

The Spring boot runs are provided by the annotation @enableautoconfiguration.

@Target ({elementtype.type})
@Retention (retentionpolicy.runtime)
@Documented
@Inherited
@ Autoconfigurationpackage
@Import ({enableautoconfigurationimportselector.class}) public
@interface enableautoconfiguration {
    String enabled_override_property = "Spring.boot.enableautoconfiguration";

    Class<?>[] Exclude () default {};

    String[] Excludename () default {};
}


The key features here are @import annotations. Enableautoconfigurationimportselector uses the Springfactoriesloader.loadfactorynames method to scan for a meat-inf/ The jar package for the Spring.factories file (the Enableautoconfigurationimportselector class was used before the 1.5 version, and after 1.5 the class was discarded using the Autoconfigurationimportselector Class). The following is part of the Spring.factories file in Meat-inf under Spring-boot-autoconfigure-1.5.4.release.jar.

# initializers Org.springframework.context.applicationcontextinitializer=\
Org.springframework.boot.autoconfigure.sharedmetadatareaderfactorycontextinitializer,\
Org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer # application Listeners
Org.springframework.context.applicationlistener=\
Org.springframework.boot.autoconfigure.BackgroundPreinitializer # Auto Configuration Import Listeners
Org.springframework.boot.autoconfigure.autoconfigurationimportlistener=\ Org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener # Auto
Configuration Import Filters org.springframework.boot.autoconfigure.autoconfigurationimportfilter=\
Org.springframework.boot.autoconfigure.condition.OnClassCondition # Auto Configure
Org.springframework.boot.autoconfigure.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,\

The classes inside are all automatic configuration classes, and Springboot will automatically configure the environment based on these automatic configuration classes.

Below we will automatically write a starter.


Ii. Custom Starter

First, we introduce several conditional annotations.

@ConditionalOnBean: When the specified bean in the container is true

@ConditionalOnClass: If the specified class is true under the Classpath

@ConditionalOnMissingBean: When no specified Bean is true in the container

@ConditionalOnProperty: Whether the specified data has the specified value

。。。。

After understanding the conditional annotation, we started customizing the starter.

1, in the custom starter before the need to fill in Maven dependencies.


<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http:// Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Cn.miaolovezhen</groupid> <artifactId>spring-boot-starter-test</artifactId> <version> 0.0.1-snapshot</version> <packaging>jar</packaging> <name>spring-boot-starter-test</ Name> <description>demo Project for Spring boot</description> <parent> <groupid>or G.springframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> <ver Sion>1.5.6.release</version> <relativePath/> <!--lookup parent from repository--> </par Ent> <properties> <project.build.sourceEncoding>Utf-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</ project.reporting.outputencoding> <java.version>1.8</java.version> </properties> &LT;DEP endencies> <dependency> <groupId>org.springframework.boot</groupId> <artif Actid>spring-boot-autoconfigure</artifactid> <version>1.5.4.RELEASE</version> &LT;/DEP
 Endency> </dependencies> </project>

2, the completion of the Testproperties class, this class defines the default property values, such as the class, only one attribute value msg, default to World. @ConfigurationProperties annotation defines a match, and if you want to modify the property value, you can modify it in application.properties using the match. Attribute = modified value. such as Test.msg = Tan

@ConfigurationProperties (prefix = "test") public
class Testproperties {
    private static final String MSG = "Spring Boot ";
    Private String msg = msg;

    Public String getmsg () {return
        msg;
    }

    public void Setmsg (String msg) {
        this.msg = msg;
    }
}

3, complete the service class. A service class is a primary functional class that, if not springboot, is required to configure the build itself in spring. such as the SPRINGMVC in the Dispatcherservlet, MyBatis DataSource and so on.


public class Testservice {
    private String msg;

    Public String SayHello () {return
        "Hello" + msg;
    }

    Public String getmsg () {return
        msg;
    }

    public void Setmsg (String msg) {
        this.msg = msg;
    }
}

4, complete the automatic configuration class. The primary role of the automatic configuration class is the Springboot configuration core, which is written in Meat-inf/spring.factories, informing Springboot to read the class at startup and configure it according to the rules of that class.

@EnableConfigurationProperties Annotations Open attribute injection according to the Testproperties class, allowing the application.properties to modify the property values inside.

@ConditionOnClass detects the existence of Testservice classes

@ConditionOnProperty class will see if the automatic configuration is turned on. The default is open (true).

@ConditionOnMissingBean detects if there is an object in the container for the Testservice class, and if not, generates one.


@Configuration
@EnableConfigurationProperties (testproperties.class)
@ConditionalOnClass ( Testservice.class)
@ConditionalOnProperty (prefix = "Test", value = "Enabled", matchifmissing = True) public
CLA SS Testserviceautoconfiguration {
    @Autowired
    testproperties testproperties;

    @Bean
    @ConditionalOnMissingBean (testservice.class) public
    testservice Testservice () {
        Testservice Testservice = new Testservice ();
        Testservice.setmsg (Testproperties.getmsg ());
        Return Testservice
    }
}

5, the final step, do not forget to create the Spring.factories file in the Meat-inf folder. The content is very simple, tell Springboot to read Testserviceauto

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.