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 }
待續......