Spring boot injects configuration properties into the Bean class

Source: Internet
Author: User

I. Use of @ConfigurationProperties annotations


Look at the configuration file, my configuration is in Yaml format:

// file application.ymlmy:  servers:    - dev.bar.com    - foo.bar.com - jiaobuchong.com
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

Now I'm going to inject the above configuration properties into a Java bean class, looking at the Code:

Import org.springframework.boot.context.properties.ConfigurationProperties;Import org.springframework.stereotype.Component;import java.util.ArrayList; import java.util.List; /** * File:MyConfig.java * Created by Jiaobuchong on 12/29/15. */ @Component //do not add this annotation, the use of @autowired can not be injected into the @ Configurationproperties (prefix =  "my") //the prefix in the configuration file public class  Myconfig {private list<string> servers = new ArrayList <String> (); public list<string> getservers () { return this.servers;}       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

Write a controller below to Test:

/** * file: Hellocontroller * Created by Jiaobuchong on 2015/12/4. */ @RequestMapping ( "/test")  @RestController public class hellocontroller { @Autowired Span class= "hljs-keyword" >private myconfig myconfig;  @RequestMapping ( "/config")  Public Object getconfig () {return myconfig.getservers ();}}  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

Run Application.java's Main method below to See:

@Configuration//a class is a configuration class, spring boot automatically loads this class-related feature when it sweeps to this annotation, such as the configuration< on the class when configuring AOP and interceptors as described in the previous article Span class= "hljs-annotation" > @EnableAutoConfiguration //enable automatic configuration of the framework to be able to conduct the configuration, To boot and run the application, automatically load the configuration according to the imported Starter-pom  @ComponentScan // Scan component @ComponentScan (value = "com.spriboot.controller") Configure the path of the scan component public class application { Public static void main (String[] Args) {//start the spring boot project's unique portal springapplication app = new Springapplication (application.class); App.setbannermode (Banner.Mode.OFF); App.run (args); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

In the address bar of the browser, type:
Localhost:8080/test/config get:
["dev.bar.com", "foo.bar.com", "jiaobuchong.com"]

Ii. @ConfigurationProperties and @enableconfigurationproperties annotations used together


The general steps for configuring with YAML in spring boot are,
1. YAML configuration file, Here are the assumptions:

my:  webserver:    #HTTP 监听端口    port: 80    #嵌入Web服务器的线程池配置    threadPool:      maxThreads: 100 minThreads: 8 idleTimeout: 60000
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

2.

File Mywebserverconfigurationproperties.javaimport org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties (prefix ="my.webserver")PublicClass Mywebserverconfigurationproperties {Privateint port;Private ThreadPool ThreadPool;PublicIntGetport () {Return port; }PublicvoidSetport (int Port) {This.port = port; }Public ThreadPoolGetthreadpool () {Return threadPool; }PublicvoidSetthreadpool (ThreadPool ThreadPool) {This.threadpool = threadPool; }PublicStaticClass ThreadPool {Privateint maxthreads;Privateint minthreads;Privateint idleTimeout;PublicIntGetidletimeout () {Return idleTimeout; }PublicvoidSetidletimeout (int IdleTimeout) {this.idletimeout = idleTimeout;} public int getMaxThreads () {return maxthreads; } public void setMaxThreads (int maxthreads) {this.maxthreads = maxthreads;} public int getminthreads () {return minthreads; } public void setMinThreads (int minthreads) {this.minthreads = minthreads;}}}     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

3.

File:MyWebServerConfiguration.javaimport org.springframework.context.annotation.Configuration; import org.springframework.boot.context.properties.enableconfigurationproperties;< Span class= "hljs-annotation" > @Configuration  @EnableConfigurationProperties ( Mywebserverconfigurationproperties.class) public class mywebserverconfiguration { @Autowired private mywebserverconfigurationproperties properties; /** * Below you can refer to the configuration in the Mywebserverconfigurationproperties class */void setmyconfig () {String port = properties.getport (); Span class= "hljs-comment" >//.....} }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17


The @enableconfigurationproperties Annotation is automatically applied to your project so, any beans Annotated with @ConfigurationProperties'll be configured from the environment Properties. This is the style of the configuration works particularly well with the Springapplication external YAML Configuration. (quoted from spring Boot official Manual)

Iii. @Bean Configuring Third-party components (third-party Configuration)

Create a bean class:

File Threadpoolbean.java/** * Created by Jiaobuchong on 1/4/16. */PublicClassThreadpoolbean {Privateint maxthreads;Privateint minthreads;Privateint idleTimeout;PublicIntGetMaxThreads () {Return maxthreads; }PublicvoidSetMaxThreads (int Maxthreads) {this.maxthreads = maxthreads;} public int getMinThreads () {return minthreads; } public void setMinThreads (int minthreads) {this.minthreads = minthreads;} public int getidletimeout () {return idleTimeout; } public void setIdleTimeout (int idleTimeout) {this.idletimeout = idleTimeout;}}    

Refer to the configuration classes written in the second part of the previous section: Mywebserverconfiguration.java and mywebserverconfigurationproperties.java, and YAML configuration files, Now modify the Mywebserverconfiguration.java class:

Import com.jiaobuchong.springboot.domain.ThreadPoolBean;Import org.springframework.beans.factory.annotation.Autowired;Import org.springframework.boot.context.properties.EnableConfigurationProperties;Import org.springframework.context.annotation.Bean;Import org.springframework.context.annotation.Configuration;/** * Created by Jiaobuchong on 1/4/16. */@ConfigurationThis is a configuration class, similar to the @service, @Component Effect. Spring will scan to this class, @Bean will take effect, register Threadpoolbean This return value class in the spring context@EnableConfigurationProperties (mywebserverconfigurationproperties. Class)With this annotation, the configuration of this class is mywebserverconfigurationproperties to the context, and the @ used in this classautowiredannotation injection to take effectPublicClassmywebserverconfiguration { @SuppressWarnings ( "springjavaautowiringinspection") Span class= "hljs-comment" >//add This annotation so that the IDE does not report: Could not autowire  @Autowired private mywebserverconfigurationproperties properties;  @Bean //@Bean annotations on a method, the return value is an instance of a class and declares the return value (returning an Object) is a bean in the spring context public threadpoolbean getthreadbean () { Mywebserverconfigurationproperties.threadpool ThreadPool = Properties.getthreadpool (); Threadpoolbean Threadpoolbean = new threadpoolbean (); threadpoolbean.setidletimeout ( Threadpool.getidletimeout ()); Threadpoolbean.setmaxthreads (threadpool.getmaxthreads ()); Threadpoolbean.setminthreads (threadpool.getminthreads ()); return threadpoolbean;}          

The class identified by the @configuration annotation, typically as a configuration class, is similar to an XML file, which indicates that bean metadata is configured in that class, which acts like a application-context.xml configuration file in spring, and @ A bean tag, which resembles a bean instance declared in the XML file.

Write a controller test:

Import com.jiaobuchong.springboot.domain.ThreadPoolBean;Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Jiaobuchong on 2015/12/4. */ @RequestMapping ( "/first")  @RestController  Public class hellocontroller { @Autowired private threadpoolbean threadpoolbean;  @RequestMapping ("/testbean ") public Object getthreadbean () {return threadpoolbean;}}    

Run Application.java's main method,
In the browser, type: Http://localhost:8080/first/testbean
The resulting return value is:
{"maxthreads": +, "minthreads": 8, "idleTimeout": 60000}

http://blog.csdn.net/jiaobuchong/article/details/50442709

Spring boot injects configuration properties into the Bean class

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.