1. 程式人生 > >SpringBoot配置分析、獲取到SpringBoot配置檔案資訊以及幾種獲取配置檔案資訊的方式

SpringBoot配置分析、獲取到SpringBoot配置檔案資訊以及幾種獲取配置檔案資訊的方式

SpringBoot的預設的配置檔案application.properties配置檔案。

1、第一種方式直接獲取到配置檔案裡面的配置資訊。 第二種方式是通過將已經注入到容器裡面的bean,然後再注入Environment這個bean進行獲取。具體操作如下所示:

 1 package com.bie.springboot;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Value;
5 import org.springframework.core.env.Environment; 6 import org.springframework.stereotype.Component; 7 8 /** 9 * 10 * @Description TODO 11 * @author biehl 12 * @Date 2018年12月30日 上午10:52:09 13 * 1、SpringBoot獲取到配置檔案配置資訊的幾種方式。 14 * 2、注意配置檔案application.properties配置檔案預設是在src/main/resources目錄下面,
15 * 也可以在src/main/resources目錄下面的config目錄下面。 16 * 即預設是在classpath根目錄,或者classpath:/config目錄。file:/,file:config/ 17 * 3、如何修改預設的配置檔名稱application.propereties或者預設的目錄位置? 18 * 預設的配置檔名字可以使用--spring.config.name指定,只需要指定檔案的名字,副檔名可以省略。 19 * 預設的配置檔案路徑可以使用--spring.config.location來指定,配置檔案需要指定全路徑,包括目錄和檔名字,還可以指定
20 * 多個,多個用逗號隔開,檔案的指定方式有兩種。1:classpath: 2:file: 21 * 第一種方式,執行的時候指定引數:--spring.config.name=app 22 * 指定目錄位置引數:--spring.config.location=classpath:conf/app.properties 23 * 24 * 25 */ 26 @Component // 註冊到Spring容器中進行管理操作 27 public class UserConfig { 28 29 // 第二種方式 30 @Autowired // 注入到容器中 31 private Environment environment; 32 33 // 第三種方式 34 @Value("${local.port}") 35 private String localPort; 36 37 // 以整數的形式獲取到配置檔案裡面的配置資訊 38 @Value("${local.port}") 39 private Integer localPort_2; 40 41 // 以預設值的形式賦予值 42 // @Value預設必須要有配置項,配置項可以為空,但是必須要有,如果沒有配置項,則可以給預設值 43 @Value("${tomcat.port:9090}") 44 private Integer tomcatPort; 45 46 /** 47 * 獲取到配置檔案的配置 48 */ 49 public void getIp() { 50 System.out.println("local.ip = " + environment.getProperty("local.ip")); 51 } 52 53 /** 54 * 以字串String型別獲取到配置檔案裡面的配置資訊 55 */ 56 public void getPort() { 57 System.out.println("local.port = " + localPort); 58 } 59 60 /** 61 * 以整數的形式獲取到配置檔案裡面的配置資訊 62 */ 63 public void getPort_2() { 64 System.out.println("local.port = " + environment.getProperty("local.port", Integer.class)); 65 System.out.println("local.port = " + localPort_2); 66 } 67 68 /** 69 * 獲取到配置檔案裡面引用配置檔案裡面的配置資訊 配置檔案裡面變數的引用操作 70 */ 71 public void getSpringBootName() { 72 System.out.println("Spring is " + environment.getProperty("springBoot")); 73 System.out.println("SpringBoot " + environment.getProperty("Application.springBoot")); 74 } 75 76 /** 77 * 以預設值的形式賦予配置檔案的值 78 */ 79 public void getTomcatPort() { 80 System.out.println("tomcat port is " + tomcatPort); 81 } 82 }

預設配置檔案叫做application.properties配置檔案,預設再src/main/resources目錄下面。

1 local.ip=127.0.0.1
2 local.port=8080
3 
4 springBoot=springBoot
5 Application.springBoot=this is ${springBoot}

然後可以使用執行類,將效果執行一下,執行類如下所示:

  1 package com.bie;
  2 
  3 import org.springframework.beans.BeansException;
  4 import org.springframework.boot.SpringApplication;
  5 import org.springframework.boot.autoconfigure.SpringBootApplication;
  6 import org.springframework.context.ConfigurableApplicationContext;
  7 
  8 import com.bie.springboot.DataSourceProperties;
  9 import com.bie.springboot.JdbcConfig;
 10 import com.bie.springboot.UserConfig;
 11 
 12 /**
 13  * 
 14  * @Description TODO
 15  * @author biehl
 16  * @Date 2018年12月30日 上午10:44:35
 17  *
 18  */
 19 @SpringBootApplication
 20 public class Application {
 21 
 22     public static void main(String[] args) {
 23         System.out.println("===================================================");
 24         ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
 25         
 26         try {
 27             //1、第一種方式,獲取application.properties配置檔案的配置
 28             System.out.println(run.getEnvironment().getProperty("local.ip"));
 29         } catch (Exception e1) {
 30             e1.printStackTrace();
 31         }
 32         
 33         System.out.println("===================================================");
 34         
 35         try {
 36             //2、第二種方式,通過注入到Spring容器中的類進行獲取到配置檔案裡面的配置
 37             run.getBean(UserConfig.class).getIp();
 38         } catch (BeansException e) {
 39             e.printStackTrace();
 40         }
 41         
 42         System.out.println("===================================================");
 43         
 44         
 45         try {
 46             //3、第三種方式,通過注入到Spring容器中的類進行獲取到@Value註解來獲取到配置檔案裡面的配置
 47             run.getBean(UserConfig.class).getPort();
 48         } catch (BeansException e) {
 49             e.printStackTrace();
 50         }
 51         
 52         System.out.println("===================================================");
 53         
 54         try {
 55             //4、可以以字串型別或者整數型別獲取到配置檔案裡面的配置資訊
 56             run.getBean(UserConfig.class).getPort_2();
 57         } catch (Exception e) {
 58             e.printStackTrace();
 59         }
 60         
 61         System.out.println("===================================================");
 62         
 63         
 64         try {
 65             //5、配置檔案裡面變數的引用操作
 66             run.getBean(UserConfig.class).getSpringBootName();
 67         } catch (Exception e) {
 68             e.printStackTrace();
 69         }
 70         
 71         System.out.println("===================================================");
 72         
 73         try {
 74             //6、以預設值的形式獲取到配置檔案的資訊
 75             run.getBean(UserConfig.class).getTomcatPort();
 76         } catch (Exception e) {
 77             e.printStackTrace();
 78         }
 79         
 80         System.out.println("===================================================");
 81         
 82         try {
 83             run.getBean(JdbcConfig.class).showJdbc();
 84         } catch (Exception e) {
 85             e.printStackTrace();
 86         }
 87         
 88         System.out.println("===================================================");
 89         
 90         try {
 91             run.getBean(DataSourceProperties.class).showJdbc();
 92         } catch (Exception e) {
 93             e.printStackTrace();
 94         }
 95         
 96         System.out.println("===================================================");
 97         
 98         //執行結束進行關閉操作
 99         run.close();
100     }
101     
102 
103     
104 }

2、也可以通過多配置檔案的方式獲取到配置檔案裡面的配置資訊,如下所示:

 1 package com.bie.springboot;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.context.annotation.PropertySource;
 5 
 6 /**
 7  * 
 8  * @Description TODO
 9  * @author biehl
10  * @Date 2018年12月30日 上午11:58:34
11  *
12  *    1、將其他的配置檔案進行載入操作。
13  *        指定多個配置檔案,這樣可以獲取到其他的配置檔案的配置資訊。
14  *    2、載入外部的配置。
15  *        PropertiesSource可以載入一個外部的配置,當然了,也可以註解多次。
16  *    
17  */
18 @Configuration
19 @PropertySource("classpath:jdbc.properties") //指定多個配置檔案,這樣可以獲取到其他的配置檔案的配置資訊
20 @PropertySource("classpath:application.properties")
21 public class JdbcFileConfig {
22 
23     
24 }

其他的配置檔案的配置資訊如下所示:

1 drivername=com.mysql.jdbc.Driver
2 url=jdbc:mysql:///book
3 user=root
4 password=123456
5 
6 ds.drivername=com.mysql.jdbc.Driver
7 ds.url=jdbc:mysql:///book
8 ds.user=root
9 ds.password=123456

然後載入配置檔案裡面的配置資訊如下所示:

執行類,見上面,不重複寫了都。

 1 package com.bie.springboot;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.stereotype.Component;
 5 
 6 /**
 7  * 
 8  * @Description TODO
 9  * @author biehl
10  * @Date 2018年12月30日 上午11:55:49
11  * 
12  * 
13  */
14 @Component
15 public class JdbcConfig {
16 
17     @Value("${drivername}")
18     private String drivername;
19     
20     @Value("${url}")
21     private String url;
22     
23     @Value("${user}")
24     private String user;
25     
26     @Value("${password}")
27     private String password;
28     
29     /**
30      * 
31      */
32     public void showJdbc() {
33         System.out.println("drivername : " + drivername 
34                 + "url : " + url 
35                 + "user : " + user 
36                 + "password : " + password);
37     }
38     
39 }
40  

3、通過獲取到配置檔案裡面的字首的方式也可以獲取到配置檔案裡面的配置資訊:

配置的配置檔案資訊,和執行的主類,在上面已經貼過來,不再敘述。

 1 package com.bie.springboot;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.stereotype.Component;
 5 
 6 /**
 7  * 
 8  * @Description TODO
 9  * @author biehl
10  * @Date 2018年12月30日 下午2:15:39
11  *
12  */
13 
14 @Component
15 @ConfigurationProperties(prefix="ds")
16 public class DataSourceProperties {
17 
18     private String drivername;
19     
20     private String url;
21     
22     private String user;
23     
24     private String password;
25     
26     /**
27      * 
28      */
29     public void showJdbc() {
30         System.out.println("drivername : " + drivername 
31                 + "url : " + url 
32                 + "user : " + user 
33                 + "password : " + password);
34     }
35 
36     public String getDrivername() {
37         return drivername;
38     }
39 
40     public void setDrivername(String drivername) {
41         this.drivername = drivername;
42     }
43 
44     public String getUrl() {
45         return url;
46     }
47 
48     public void setUrl(String url) {
49         this.url = url;
50     }
51 
52     public String getUser() {
53         return user;
54     }
55 
56     public void setUser(String user) {
57         this.user = user;
58     }
59 
60     public String getPassword() {
61         return password;
62     }
63 
64     public void setPassword(String password) {
65         this.password = password;
66     }
67     
68     
69 }

 執行效果如下所示:

 1 ===================================================
 2 
 3   .   ____          _            __ _ _
 4  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
 5 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 6  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 7   '  |____| .__|_| |_|_| |_\__, | / / / /
 8  =========|_|==============|___/=/_/_/_/
 9  :: Spring Boot ::       (v1.5.10.RELEASE)
10 
11 2018-12-30 14:36:10.116  INFO 8284 --- [           main] com.bie.Application                      : Starting Application on DESKTOP-T450s with PID 8284 (E:\eclipeswork\guoban\spring-boot-hello\target\classes started by Aiyufei in E:\eclipeswork\guoban\spring-boot-hello)
12 2018-12-30 14:36:10.121  INFO 8284 --- [           main] com.bie.Application                      : No active profile set, falling back to default profiles: default
13 2018-12-30 14:36:10.229  INFO 8284 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]140e5a13: startup date [Sun Dec 30 14:36:10 CST 2018]; root of context hierarchy
14 2018-12-30 14:36:13.451  INFO 8284 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
15 2018-12-30 14:36:13.465  INFO 8284 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
16 2018-12-30 14:36:13.467  INFO 8284 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
17 2018-12-30 14:36:13.650  INFO 8284 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
18 2018-12-30 14:36:13.651  INFO 8284 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3427 ms
19 2018-12-30 14:36:14.199  INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
20 2018-12-30 14:36:14.205  INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
21 2018-12-30 14:36:14.206  INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
22 2018-12-30 14:36:14.207  INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
23 2018-12-30 14:36:14.207  INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
24 2018-12-30 14:36:15.579  INFO 8284 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]140e5a13: startup date [Sun Dec 30 14:36:10 CST 2018]; root of context hierarchy
25 2018-12-30 14:36:15.905  INFO 8284 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.bie.action.HelloWorld.helloWorld()
26 2018-12-30 14:36:15.948  INFO 8284 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
27 2018-12-30 14:36:15.949  INFO 8284 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
28 2018-12-30 14:36:16.253  INFO 8284 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
29 2018-12-30 14:36:16.253  INFO 8284 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
30 2018-12-30 14:36:16.404  INFO 8284 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
31 2018-12-30 14:36:17.036  INFO 8284 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
32 2018-12-30 14:36:17.383  INFO 8284 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
33 2018-12-30 14:36:17.394  INFO 8284 --- [           main] com.bie.Application                      : Started Application in 7.831 seconds (JVM running for 8.598)
34 127.0.0.1
35 ===================================================
36 local.ip = 127.0.0.1
37 ===================================================
38 local.port = 8080
39 ===================================================
40 local.port = 8080
41 local.port = 8080
42 ===================================================
43 Spring is springBoot
44 SpringBoot this is springBoot
45 ===================================================
46 tomcat port is 9090
47 ===================================================
48 drivername : com.mysql.jdbc.Driverurl : jdbc:mysql:///bookuser : rootpassword : 123456
49 ===================================================
50 drivername : com.mysql.jdbc.Driverurl : jdbc:mysql:///bookuser : rootpassword : 123456
51 ===================================================
52 2018-12-30 14:36:17.403  INFO 8284 --- [           main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot[email protected]140e5a13: startup date [Sun Dec 30 14:36:10 CST 2018]; root of context hierarchy
53 2018-12-30 14:36:17.405  INFO 8284 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

 

待續......