Spring boot將配置屬性注入到bean類中


一、@ConfigurationProperties注解的使用

看配置文件,我的是yaml格式的配置:

// file application.yml
my:
  servers:
    - dev.bar.com
    - foo.bar.com
    - jiaobuchong.com

下面我要將上面的配置屬性注入到一個Java Bean類中,看碼:

 1 import org.springframework.boot.context.properties.ConfigurationProperties;
 2 import org.springframework.stereotype.Component;
 3 
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 /**
 8  * file: MyConfig.java
 9  * Created by jiaobuchong on 12/29/15.
10  */
11 @Component      //不加這個注解的話, 使用@Autowired 就不能注入進去了
12 @ConfigurationProperties(prefix = "my")  // 配置文件中的前綴
13 public class MyConfig {
14     private List<String> servers = new ArrayList<String>();
15     public List<String> getServers() { return this.servers;
16     }
17 }

下面寫一個Controller來測試一下:

 1 /**
 2  * file: HelloController
 3  * Created by jiaobuchong on 2015/12/4.
 4  */
 5 @RequestMapping("/test")
 6 @RestController
 7 public class HelloController {
 8     @Autowired
 9     private MyConfig myConfig;
10 
11     @RequestMapping("/config")
12     public Object getConfig() {
13         return myConfig.getServers();
14     }
15 }

下面運行Application.java的main方法跑一下看看:

 1 @Configuration   //標注一個類是配置類,spring boot在掃到這個注解時自動加載這個類相關的功能,比如前面的文章中介紹的配置AOP和攔截器時加在類上的Configuration
 2 @EnableAutoConfiguration  //啟用自動配置 該框架就能夠進行行為的配置,以引導應用程序的啟動與運行, 根據導入的starter-pom 自動加載配置
 3 @ComponentScan  //掃描組件 @ComponentScan(value = "com.spriboot.controller") 配置掃描組件的路徑
 4 public class Application {
 5     public static void main(String[] args) {
 6         // 啟動Spring Boot項目的唯一入口
 7         SpringApplication app = new SpringApplication(Application.class);
 8         app.setBannerMode(Banner.Mode.OFF);
 9         app.run(args);
10     }

在瀏覽器的地址欄里輸入: 
localhost:8080/test/config 得到: 
[“dev.bar.com”,”foo.bar.com”,”jiaobuchong.com”] 

二、@ConfigurationProperties和@EnableConfigurationProperties注解結合使用


在spring boot中使用yaml進行配置的一般步驟是, 
1、yaml配置文件,這里假設: 

 

my:
  webserver:
    #HTTP 監聽端口
    port: 80
    #嵌入Web服務器的線程池配置
    threadPool:
      maxThreads: 100
      minThreads: 8
      idleTimeout: 60000

 

2、

 1 //file MyWebServerConfigurationProperties.java
 2 import org.springframework.boot.context.properties.ConfigurationProperties;
 3 
 4 @ConfigurationProperties(prefix = "my.webserver")
 5 public class MyWebServerConfigurationProperties {
 6     private int port;
 7     private ThreadPool threadPool;
 8 
 9     public int getPort() {
10         return port;
11     }
12 
13     public void setPort(int port) {
14         this.port = port;
15     }
16 
17     public ThreadPool getThreadPool() {
18         return threadPool;
19     }
20 
21     public void setThreadPool(ThreadPool threadPool) {
22         this.threadPool = threadPool;
23     }
24 
25     public static class ThreadPool {
26         private int maxThreads;
27         private int minThreads;
28         private int idleTimeout;
29 
30         public int getIdleTimeout() {
31             return idleTimeout;
32         }
33 
34         public void setIdleTimeout(int idleTimeout) {
35             this.idleTimeout = idleTimeout;
36         }
37 
38         public int getMaxThreads() {
39             return maxThreads;
40         }
41 
42         public void setMaxThreads(int maxThreads) {
43             this.maxThreads = maxThreads;
44         }
45 
46         public int getMinThreads() {
47             return minThreads;
48         }
49 
50         public void setMinThreads(int minThreads) {
51             this.minThreads = minThreads;
52         }
53     }
54 }

3、

 1 // file: MyWebServerConfiguration.java
 2 import org.springframework.context.annotation.Configuration;
 3 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 4 
 5 @Configuration
 6 @EnableConfigurationProperties(MyWebServerConfigurationProperties.class)
 7 public class MyWebServerConfiguration {
 8     @Autowired
 9     private MyWebServerConfigurationProperties properties;
10     /**
11      *下面就可以引用MyWebServerConfigurationProperties類       里的配置了
12     */
13    public void setMyconfig() {
14        String port = properties.getPort();
15        // ...........
16    }   
17 }

The @EnableConfigurationProperties annotation is automatically applied to your project so that any beans annotated with @ConfigurationProperties will be configured from the Environment properties. This style of configuration works particularly well with the SpringApplication external YAML configuration.(引自spring boot官方手冊) 

三、@Bean配置第三方組件(Third-party configuration)

創建一個bean類:

 

 1 // file ThreadPoolBean.java
 2 /**
 3  * Created by jiaobuchong on 1/4/16.
 4  */
 5 public class ThreadPoolBean {
 6     private int maxThreads;
 7     private int minThreads;
 8     private int idleTimeout;
 9 
10     public int getMaxThreads() {
11         return maxThreads;
12     }
13 
14     public void setMaxThreads(int maxThreads) {
15         this.maxThreads = maxThreads;
16     }
17 
18     public int getMinThreads() {
19         return minThreads;
20     }
21 
22     public void setMinThreads(int minThreads) {
23         this.minThreads = minThreads;
24     }
25 
26     public int getIdleTimeout() {
27         return idleTimeout;
28     }
29 
30     public void setIdleTimeout(int idleTimeout) {
31         this.idleTimeout = idleTimeout;
32     }
33 }

 

引用前面第二部分寫的配置類:MyWebServerConfiguration.java和MyWebServerConfigurationProperties.java以及yaml配置文件,現在修改MyWebServerConfiguration.java類:

 1 import com.jiaobuchong.springboot.domain.ThreadPoolBean;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 
 7 /**
 8  * Created by jiaobuchong on 1/4/16.
 9  */
10 @Configuration  //這是一個配置類,與@Service、@Component的效果類似。spring會掃描到這個類,@Bean才會生效,將ThreadPoolBean這個返回值類注冊到spring上下文環境中
11 @EnableConfigurationProperties(MyWebServerConfigurationProperties.class) //通過這個注解, 將MyWebServerConfigurationProperties這個類的配置到上下文環境中,本類中使用的@Autowired注解注入才能生效
12 public class MyWebServerConfiguration {
13     @SuppressWarnings("SpringJavaAutowiringInspection") //加這個注解讓IDE 不報: Could not autowire
14     @Autowired
15     private MyWebServerConfigurationProperties properties;
16 
17     @Bean //@Bean注解在方法上,返回值是一個類的實例,並聲明這個返回值(返回一個對象)是spring上下文環境中的一個bean
18     public ThreadPoolBean getThreadBean() {
19         MyWebServerConfigurationProperties.ThreadPool threadPool = properties.getThreadPool();
20         ThreadPoolBean threadPoolBean = new ThreadPoolBean();
21         threadPoolBean.setIdleTimeout(threadPool.getIdleTimeout());
22         threadPoolBean.setMaxThreads(threadPool.getMaxThreads());
23         threadPoolBean.setMinThreads(threadPool.getMinThreads());
24         return threadPoolBean;
25     }
26 }

被@Configuration注解標識的類,通常作為一個配置類,這就類似於一個xml文件,表示在該類中將配置Bean元數據,其作用類似於Spring里面application-context.xml的配置文件,而@Bean標簽,則類似於該xml文件中,聲明的一個bean實例。 
寫一個controller測試一下:

 1 import com.jiaobuchong.springboot.domain.ThreadPoolBean;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 /**
 7  * Created by jiaobuchong on 2015/12/4.
 8  */
 9 @RequestMapping("/first")
10 @RestController
11 public class HelloController {
12     @Autowired
13     private ThreadPoolBean threadPoolBean;
14     @RequestMapping("/testbean")
15     public Object getThreadBean() {
16         return threadPoolBean;
17     }
18 
19 }

 

運行Application.java的main方法, 
在瀏覽器里輸入:http://localhost:8080/first/testbean 
得到的返回值是: 
{“maxThreads”:100,”minThreads”:8,”idleTimeout”:60000} 

ok,fucking nice

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM