Spring Boot automatic Configuration implementation

Source: Internet
Author: User

Since spring boot was used, it was forgotten that the XML configuration in spring MVC was something that could never be returned. Why spring boot so good, the convention is larger than the configuration of the original design, let us only know the maintenance of the application.properties (or application.yml) file, we can set the data source parameters in the configuration file, You can set up a service port, set up the Redis address, and so on. We often look at some jar packages that contain starter names, such as Spring-boot-starter-data-redis, and we can easily and quickly configure them by introducing these jar packages. So we have developed an interface service for others to call, can we encapsulate it into a starter jar package? Let others define in Application.properties, implement automatic configuration? The answer is yes, let me write an automatic configuration jar package with me. (The purpose of this article is not to explain the principle of automatic configuration, we can search the principle of the Internet).

  1. Environmental information

    Development tools: Idea

    Maven Version number: 3.5.4

  2. Jar Package Encapsulation

    Create a Springboot Project

    Fill in the coordinate information

    Springboot version 2.0.4

    Other default, after creation is complete, the directory is as follows

    Next, create our test service class Testservice

    1  PackageCom.tanghuachun.teststarter;2 3  Public classTestservice {4 5     PrivateString IP;6     Private intPort;7 8      PublicTestservice (String IP,intPort) {9          This. IP =IP;Ten          This. Port =Port; One     } A      -      Public voidPrintconfinfo () { -System.out.println ("Sao years, you configure the IP for:" + IP + ", Port:" +port); the     } -}

    We envision that when others use our interface, the IP and port are injected via application.properties, and then we create the attribute configuration entity class Testserviceproperties

    1  PackageCom.tanghuachun.teststarter;2 3 Importorg.springframework.boot.context.properties.ConfigurationProperties;4 5@ConfigurationProperties (prefix = "Test-config")//take the configuration file prefix to test-config configuration6  Public classtestserviceproperties {7     PrivateString host;8     Private intPort;9 Ten      PublicString gethost () { One         returnhost; A     } -  -      Public voidSethost (String host) { the          This. Host =host; -     } -  -      Public intGetport () { +         returnPort; -     } +  A      Public voidSetport (intPort) { at          This. Port =Port; -     } -}

    We found that after this class was written, we were prompted with errors.

    Add a dependency package to the Pom file and solve the problem

    <Dependency>    <groupId>Org.springframework.boot</groupId>    <Artifactid>Spring-boot-configuration-processor</Artifactid>    <Optional>True</Optional></Dependency>

    Create a new automatic configuration class Testserviceautoconfiguration

    1  PackageCom.tanghuachun.teststarter;2 3 ImportOrg.springframework.boot.autoconfigure.condition.ConditionalOnClass;4 ImportOrg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;5 ImportOrg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;6 Importorg.springframework.boot.context.properties.EnableConfigurationProperties;7 ImportOrg.springframework.context.annotation.Bean;8 Importorg.springframework.context.annotation.Configuration;9 Ten @Configuration One@ConditionalOnClass (Testservice.class)//exists testservice This class before assembling the current class A@ConditionalOnProperty (name = "Test-config.enabled", Havingvalue = "true", matchifmissing =true)//The configuration file exists for this test-config.enabled=true to start, allowing the configuration to not exist -@EnableConfigurationProperties (testserviceproperties.class) -  Public classtestserviceautoconfiguration { the @Bean -@ConditionalOnMissingBean//no testservice to assemble this class . -      Publictestservice Testservice (testserviceproperties testserviceproperties) { -         return NewTestservice (Testserviceproperties.gethost (), Testserviceproperties.getport ()); +     } -}

    The relevant annotation meaning has been explained in the comments, here, the code has been written, we want to use annotations to the user, customize an annotation @enabletestservice

    1  PackageCom.tanghuachun.teststarter;2 ImportOrg.springframework.context.annotation.Import;3 Importjava.lang.annotation.*;4 5 @Inherited6 @Documented7 @Target (Elementtype.type)8 @Retention (retentionpolicy.runtime)9@Import (testserviceautoconfiguration.class)Ten //equivalent to using the definition spring.factories to complete the automatic assembly of the Bean One  Public@InterfaceEnabletestservice { A //@Import (Testserviceautoconfiguration.class) needs to add the annotation to the caller's main class to be equivalent to the spring.factories file configuration -}

    Then comment out the Maven plugin in the Pom file, as

    Then maven packs it, and a jar package is generated that we can use directly.

    Here because in the local environment test, we install the compiled jar to the local MAVEN repository, click on the right of the Install button (you can also import a compiled jar package)

  3. Jar Package Use

    Let's start by testing our packaged jar, first creating a Springboot project (the default is when you create it, and your package name can be the same as me, it doesn't matter)

    The dependency configuration of the Pom file is as follows

    <Dependencies>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-web</Artifactid>        </Dependency>        <Dependency>            <groupId>Com.tanghuachun</groupId>            <Artifactid>Test-starter</Artifactid>            <version>0.0.1-snapshot</version>        </Dependency>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-test</Artifactid>            <Scope>Test</Scope>        </Dependency></Dependencies>

    Add annotations to the main entry class

    Create a TestController class

    1  PackageCom.tanghuachun.testmain;2 3 ImportCom.tanghuachun.teststarter.TestService;4 Importorg.springframework.beans.factory.annotation.Autowired;5 Importorg.springframework.web.bind.annotation.GetMapping;6 ImportOrg.springframework.web.bind.annotation.RestController;7 8 @RestController9  Public classTestController {Ten @Autowired One     PrivateTestservice Testservice; A  -@GetMapping (value = "/test") -      PublicString Test () { the testservice.printconfinfo (); -         return"OK"; -     } -}

    Next, configure the parameters in Application.properties

    Start the project, enter Http://localhost:8080/test carriage return in the Address bar, and look at the information that the console prints exactly what we need.

    Here we have completed an automatic configuration of the package.

    You can study the effects of annotations @conditionalonproperty on use in starter.

    The story of today is finished.

Spring Boot automatic Configuration implementation

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.