SpringBoot配置分析、获取到SpringBoot配置文件信息以及几种获取配置文件信息的方式
Spring入门篇:https://www.cnblogs.com/biehongli/p/10170241.html
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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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
4、SpringBoot注入集合、数组的操作如下所示:
1 package com.bie.springboot; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.List; 6 7 import org.springframework.boot.context.properties.ConfigurationProperties; 8 import org.springframework.stereotype.Component; 9 10 /** 11 * 12 * @Description TODO 13 * @author biehl 14 * @Date 2018年12月30日 下午2:51:05 15 * 1、注入集合 16 * 支持获取数组,集合。配置方式为:name[index]=value 17 */ 18 @Component 19 @ConfigurationProperties(prefix = "ds") 20 public class TomcatProperties { 21 22 private List<String> hosts = new ArrayList<String>(); 23 private String[] ports; 24 25 public List<String> getHosts() { 26 return hosts; 27 } 28 29 public void setHosts(List<String> hosts) { 30 this.hosts = hosts; 31 } 32 33 public String[] getPorts() { 34 return ports; 35 } 36 37 public void setPorts(String[] ports) { 38 this.ports = ports; 39 } 40 41 @Override 42 public String toString() { 43 return "TomcatProperties [hosts=" + hosts.toString() + ", ports=" + Arrays.toString(ports) + "]"; 44 } 45 46 47 48 }
默认的配置文件application.properties的内容如下所示:
1 ds.hosts[0]=192.168.11.11 2 ds.hosts[1]=192.168.11.12 3 ds.hosts[2]=192.168.11.13 4 #ds.hosts[3]=192.168.11.14 5 #ds.hosts[4]=192.168.11.15 6 7 ds.ports[0]=8080 8 ds.ports[1]=8070 9 ds.ports[2]=8090
主类如下所示:
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.TomcatProperties; 11 import com.bie.springboot.UserConfig; 12 13 /** 14 * 15 * @Description TODO 16 * @author biehl 17 * @Date 2018年12月30日 上午10:44:35 18 * 19 */ 20 @SpringBootApplication 21 public class Application { 22 23 public static void main(String[] args) { 24 ConfigurableApplicationContext run = SpringApplication.run(Application.class, args); 25 26 System.out.println("==================================================="); 27 28 try { 29 // 注入集合 30 TomcatProperties bean = run.getBean(TomcatProperties.class); 31 System.out.println(bean); 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } 35 36 System.out.println("==================================================="); 37 38 // 运行结束进行关闭操作 39 run.close(); 40 } 41 42 }
待续......