Learn: Write an automatic configuration for spring boot

Source: Internet
Author: User

Spring boot follows the "Convention due to configuration" principle, using annotation to make default configurations for some of the regular configuration items, and to reduce or not use the XML configuration to get your project up and running quickly. The magic of Spring boot is not achieved by the generation of code, but by conditional annotations.

The automatic configuration of autoconfiguration is an important principle for implementing spring boot, and understanding how Autoconfiguration works is particularly important, and writing a autoconfiguration can deepen our The boot understanding.

1. Define Type-safe Configuration Properties
@ConfigurationProperties ("Author")//1 Public classAuthorpropertis {Private Static FinalString NAME = "Pyj"; Private Static FinalString PWD = "12324"; PrivateString name =NAME;//2PrivateString pwd =PWD; Privatestring[] ARRAYPROPS;//3PrivateProperties Properties =NewProperties ();//4Privatelist<map<string, object>> listProp1 =NewArrayList ();//5PrivateList<string> LISTPROP2 =NewArrayList ();//6Privatemap<string, object> mapprops =NewHashMap ();//7 getter and setter ...}

1. @ConfigurationProperties mapping APPLICATION.YML configuration prefixed with author

2, the default value of Author.name is Pyj

3-7: Property injection for Container objects

2. Define a simple bean
 Public class HelloService {    private  String msg;
Getter and setter ...
}

Note: You don't have to tangle with helloservice content, it's a simple bean.

3. Define Autoconfiguration
@Configuration//1@conditionalonclass (helloservice.class)//2@enableconfigurationproperties (authorpropertis.class)//3@conditionalonproperty (prefix= "Author", value = "Enabled", matchifmissing =true)//4 Public classauthorautoconfiguration {Private FinalAuthorpropertis Authorpropertis;  Publicauthorautoconfiguration (Authorpropertis authorpropertis) {//5 This. Authorpropertis =Authorpropertis; } @Bean//6 @ConditionalOnMissingBean (helloservice.class)//7 PublicHelloService HelloService ()throwsjsonprocessingexception {helloservice HelloService=NewHelloService (); Helloservice.setmsg (Authorpropertis.getname ()+" :" +authorpropertis.getpwd ()); Objectmapper Objectmapper=NewObjectmapper (); System.out.println ("Arrayprops:" +objectmapper.writevalueasstring (Authorpropertis.getarrayprops ())); System.out.println ("LISTPROP1:" +objectmapper.writevalueasstring (AUTHORPROPERTIS.GETLISTPROP1 ())); System.out.println ("LISTPROP2:" +objectmapper.writevalueasstring (AUTHORPROPERTIS.GETLISTPROP2 ())); System.out.println ("Mapprops:" +objectmapper.writevalueasstring (Authorpropertis.getmapprops ())); System.out.println ("Props:" +objectmapper.writevalueasstring (Authorpropertis.getproperties ())); returnHelloService; }}

1. @Configuration declared as a configuration class

2. @ConditionalOnClass means that HelloService is called when it is under the Classpath

3, @EnableConfigurationProperties the use of Authorpropertis configuration

4, @ConditionalOnProperty The specified author whether there is a default value

5. Inject Authorpropertis

6-7. When there is no helloservice bean, create a new HelloService bean

4. Register in Spring.factories
org.springframework.boot.autoconfigure.enableautoconfiguration=   Com.github.gin.springboot.config.AuthorAutoConfiguration

In the resources new Meta-inf directory, then new spring.factories, register on authorautoconfiguration, let Spring boot know for you to automatically configure.

If you do not understand this principle, you can see @enableautoconfiguration through @import ({enableautoconfigurationimportselector.class}) To read spring.factories

5. configuration file Application.yml
true Author:  name:pyj  1234Properties:    ' true' ' true '       LISTPROP1:    - name:abc      Value:sgaw    - name:efg      value:sagsag  listProp2 :    - config2value1    - config2vavlue2  mapprops:    true      true1,2,3,4,5  
6. Testing
@RestController  Public class TestController {    @Autowired    helloservice helloservice;    @RequestMapping ("/")    public  String Index () {        return "Hello world! " ;    }    @RequestMapping ("/hello")    public  String Hello () {        return  helloservice.getmsg ();    }}

Run MVN Spring-boot:run, if you see the results, then the proof is no problem

The above Authorpropertis, HelloService, authorautoconfiguration can be used as a standalone starter POM to provide a common service for other projects. Although spring boot covers most of the usage scenarios, but not all of them, for example MyBatis does not have spring boot automatic configuration, so we can use Autoconfiguration to play the same effect.

Instance code address: Have love to pick up

Learn: Write an automatic configuration for spring boot

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.