Spring入门篇:https://www.cnblogs.com/biehongli/p/10170241.html

SpringBoot的默认的配置文件application.properties配置文件。

1、第一种方式直接获取到配置文件里面的配置信息。 第二种方式是通过将已经注入到容器里面的bean,然后再注入Environment这个bean进行获取。具体操作如下所示:

 package com.bie.springboot;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 上午10:52:09
* 1、SpringBoot获取到配置文件配置信息的几种方式。
* 2、注意配置文件application.properties配置文件默认是在src/main/resources目录下面,
* 也可以在src/main/resources目录下面的config目录下面。
* 即默认是在classpath根目录,或者classpath:/config目录。file:/,file:config/
* 3、如何修改默认的配置文件名称application.propereties或者默认的目录位置?
* 默认的配置文件名字可以使用--spring.config.name指定,只需要指定文件的名字,文件扩展名可以省略。
* 默认的配置文件路径可以使用--spring.config.location来指定,配置文件需要指定全路径,包括目录和文件名字,还可以指定
* 多个,多个用逗号隔开,文件的指定方式有两种。1:classpath: 2:file:
* 第一种方式,运行的时候指定参数:--spring.config.name=app
* 指定目录位置参数:--spring.config.location=classpath:conf/app.properties
*
*
*/
@Component // 注册到Spring容器中进行管理操作
public class UserConfig { // 第二种方式
@Autowired // 注入到容器中
private Environment environment; // 第三种方式
@Value("${local.port}")
private String localPort; // 以整数的形式获取到配置文件里面的配置信息
@Value("${local.port}")
private Integer localPort_2; // 以默认值的形式赋予值
// @Value默认必须要有配置项,配置项可以为空,但是必须要有,如果没有配置项,则可以给默认值
@Value("${tomcat.port:9090}")
private Integer tomcatPort; /**
* 获取到配置文件的配置
*/
public void getIp() {
System.out.println("local.ip = " + environment.getProperty("local.ip"));
} /**
* 以字符串String类型获取到配置文件里面的配置信息
*/
public void getPort() {
System.out.println("local.port = " + localPort);
} /**
* 以整数的形式获取到配置文件里面的配置信息
*/
public void getPort_2() {
System.out.println("local.port = " + environment.getProperty("local.port", Integer.class));
System.out.println("local.port = " + localPort_2);
} /**
* 获取到配置文件里面引用配置文件里面的配置信息 配置文件里面变量的引用操作
*/
public void getSpringBootName() {
System.out.println("Spring is " + environment.getProperty("springBoot"));
System.out.println("SpringBoot " + environment.getProperty("Application.springBoot"));
} /**
* 以默认值的形式赋予配置文件的值
*/
public void getTomcatPort() {
System.out.println("tomcat port is " + tomcatPort);
}
}

默认配置文件叫做application.properties配置文件,默认再src/main/resources目录下面。

 local.ip=127.0.0.1
local.port= springBoot=springBoot
Application.springBoot=this is ${springBoot}

然后可以使用运行类,将效果运行一下,运行类如下所示:

 package com.bie;

 import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; import com.bie.springboot.DataSourceProperties;
import com.bie.springboot.JdbcConfig;
import com.bie.springboot.UserConfig; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 上午10:44:35
*
*/
@SpringBootApplication
public class Application { public static void main(String[] args) {
System.out.println("===================================================");
ConfigurableApplicationContext run = SpringApplication.run(Application.class, args); try {
//1、第一种方式,获取application.properties配置文件的配置
System.out.println(run.getEnvironment().getProperty("local.ip"));
} catch (Exception e1) {
e1.printStackTrace();
} System.out.println("==================================================="); try {
//2、第二种方式,通过注入到Spring容器中的类进行获取到配置文件里面的配置
run.getBean(UserConfig.class).getIp();
} catch (BeansException e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
//3、第三种方式,通过注入到Spring容器中的类进行获取到@Value注解来获取到配置文件里面的配置
run.getBean(UserConfig.class).getPort();
} catch (BeansException e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
//4、可以以字符串类型或者整数类型获取到配置文件里面的配置信息
run.getBean(UserConfig.class).getPort_2();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
//5、配置文件里面变量的引用操作
run.getBean(UserConfig.class).getSpringBootName();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
//6、以默认值的形式获取到配置文件的信息
run.getBean(UserConfig.class).getTomcatPort();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
run.getBean(JdbcConfig.class).showJdbc();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); try {
run.getBean(DataSourceProperties.class).showJdbc();
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); //运行结束进行关闭操作
run.close();
} }

2、也可以通过多配置文件的方式获取到配置文件里面的配置信息,如下所示:

 package com.bie.springboot;

 import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 上午11:58:34
*
* 1、将其他的配置文件进行加载操作。
* 指定多个配置文件,这样可以获取到其他的配置文件的配置信息。
* 2、加载外部的配置。
* PropertiesSource可以加载一个外部的配置,当然了,也可以注解多次。
*
*/
@Configuration
@PropertySource("classpath:jdbc.properties") //指定多个配置文件,这样可以获取到其他的配置文件的配置信息
@PropertySource("classpath:application.properties")
public class JdbcFileConfig { }

其他的配置文件的配置信息如下所示:

 drivername=com.mysql.jdbc.Driver
url=jdbc:mysql:///book
user=root
password= ds.drivername=com.mysql.jdbc.Driver
ds.url=jdbc:mysql:///book
ds.user=root
ds.password=

然后加载配置文件里面的配置信息如下所示:

运行类,见上面,不重复写了都。

 package com.bie.springboot;

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 上午11:55:49
*
*
*/
@Component
public class JdbcConfig { @Value("${drivername}")
private String drivername; @Value("${url}")
private String url; @Value("${user}")
private String user; @Value("${password}")
private String password; /**
*
*/
public void showJdbc() {
System.out.println("drivername : " + drivername
+ "url : " + url
+ "user : " + user
+ "password : " + password);
} }

3、通过获取到配置文件里面的前缀的方式也可以获取到配置文件里面的配置信息:

配置的配置文件信息,和运行的主类,在上面已经贴过来,不再叙述。

 package com.bie.springboot;

 import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 下午2:15:39
*
*/ @Component
@ConfigurationProperties(prefix="ds")
public class DataSourceProperties { private String drivername; private String url; private String user; private String password; /**
*
*/
public void showJdbc() {
System.out.println("drivername : " + drivername
+ "url : " + url
+ "user : " + user
+ "password : " + password);
} public String getDrivername() {
return drivername;
} public void setDrivername(String drivername) {
this.drivername = drivername;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public String getUser() {
return user;
} public void setUser(String user) {
this.user = user;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

运行效果如下所示:

 ===================================================

   .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE) -- ::10.116 INFO --- [ main] com.bie.Application : Starting Application on DESKTOP-T450s with PID (E:\eclipeswork\guoban\spring-boot-hello\target\classes started by Aiyufei in E:\eclipeswork\guoban\spring-boot-hello)
-- ::10.121 INFO --- [ main] com.bie.Application : No active profile set, falling back to default profiles: default
-- ::10.229 INFO --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@140e5a13: startup date [Sun Dec :: CST ]; root of context hierarchy
-- ::13.451 INFO --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): (http)
-- ::13.465 INFO --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
-- ::13.467 INFO --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.
-- ::13.650 INFO --- [ost-startStop-] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
-- ::13.651 INFO --- [ost-startStop-] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in ms
-- ::14.199 INFO --- [ost-startStop-] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
-- ::14.205 INFO --- [ost-startStop-] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-12-30 14:36:14.206 INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-12-30 14:36:14.207 INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-12-30 14:36:14.207 INFO 8284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
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
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()
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)
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)
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]
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]
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]
-- ::17.036 INFO --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
-- ::17.383 INFO --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): (http)
-- ::17.394 INFO --- [ main] com.bie.Application : Started Application in 7.831 seconds (JVM running for 8.598)
127.0.0.1
===================================================
local.ip = 127.0.0.1
===================================================
local.port =
===================================================
local.port =
local.port =
===================================================
Spring is springBoot
SpringBoot this is springBoot
===================================================
tomcat port is
===================================================
drivername : com.mysql.jdbc.Driverurl : jdbc:mysql:///bookuser : rootpassword : 123456
===================================================
drivername : com.mysql.jdbc.Driverurl : jdbc:mysql:///bookuser : rootpassword : 123456
===================================================
-- ::17.403 INFO --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@140e5a13: startup date [Sun Dec :: CST ]; root of context hierarchy
-- ::17.405 INFO --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown

4、SpringBoot注入集合、数组的操作如下所示:

 package com.bie.springboot;

 import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 下午2:51:05
* 1、注入集合
* 支持获取数组,集合。配置方式为:name[index]=value
*/
@Component
@ConfigurationProperties(prefix = "ds")
public class TomcatProperties { private List<String> hosts = new ArrayList<String>();
private String[] ports; public List<String> getHosts() {
return hosts;
} public void setHosts(List<String> hosts) {
this.hosts = hosts;
} public String[] getPorts() {
return ports;
} public void setPorts(String[] ports) {
this.ports = ports;
} @Override
public String toString() {
return "TomcatProperties [hosts=" + hosts.toString() + ", ports=" + Arrays.toString(ports) + "]";
} }

默认的配置文件application.properties的内容如下所示:

 ds.hosts[]=192.168.11.11
ds.hosts[]=192.168.11.12
ds.hosts[]=192.168.11.13
#ds.hosts[]=192.168.11.14
#ds.hosts[]=192.168.11.15 ds.ports[]=
ds.ports[]=
ds.ports[]=

主类如下所示:

 package com.bie;

 import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; import com.bie.springboot.DataSourceProperties;
import com.bie.springboot.JdbcConfig;
import com.bie.springboot.TomcatProperties;
import com.bie.springboot.UserConfig; /**
*
* @Description TODO
* @author biehl
* @Date 2018年12月30日 上午10:44:35
*
*/
@SpringBootApplication
public class Application { public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(Application.class, args); System.out.println("==================================================="); try {
// 注入集合
TomcatProperties bean = run.getBean(TomcatProperties.class);
System.out.println(bean);
} catch (Exception e) {
e.printStackTrace();
} System.out.println("==================================================="); // 运行结束进行关闭操作
run.close();
} }

待续......

SpringBoot配置分析、获取到SpringBoot配置文件信息以及几种获取配置文件信息的方式的更多相关文章

  1. springBoot配置分析(属性和结构化)

    使用idea自带插件创建项目 一直下一步到完成 application.properties local.ip.addr = 192.168.2.110 redis.host = 192.168.3. ...

  2. React中ref的三种用法 可以用来获取表单中的值 这一种类似document.getXXId的方式

    import React, { Component } from "react" export default class MyInput extends Component { ...

  3. SpringBoot配置属性之NOSQL

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

  4. SpringBoot配置属性之Migration

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

  5. SpringBoot配置属性之Security

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

  6. SpringBoot配置属性之MVC

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

  7. SpringBoot 配置的加载

    SpringBoot 配置的加载 SpringBoot配置及环境变量的加载提供许多便利的方式,接下来一起来学习一下吧! 本章内容的源码按实战过程采用小步提交,可以按提交的节点一步一步来学习,仓库地址: ...

  8. SpringBoot配置属性之Server

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

  9. SpringBoot配置属性转载地址

    SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...

随机推荐

  1. 解决mysql中文乱码问题 在url后面添加?characterEncoding=utf8

  2. bugku web web基础

    web基础$_GET $what=$_GET['what'];echo $what;if($what=='flag')echo 'flag{****}'; 看了这段代码知道,需要用get提交what= ...

  3. Ueditor注意的地方

    复制粘贴内容到编辑器上时,一些标签的属性会被过滤,在config.js里添加白名单配置项,例如: whitList: { a: ['target', 'href', 'title', 'class', ...

  4. python dic字典使用

    #!/usr/bin/env python -*-''' 字典的基本组成及用法: dict={key:value} dict[key]=value 字典是无序的. key值是唯一属性,一对一,几个ke ...

  5. maven 构建参数和命令

    mvn常用参数 mvn -e 显示详细错误 mvn -U 强制更新snapshot类型的插件或依赖库(否则maven一天只会更新一次snapshot依赖) mvn -o 运行offline模式,不联网 ...

  6. 第九节: 利用RemoteScheduler实现Sheduler的远程控制

    一. RemoteScheduler远程控制 1. 背景: 在A服务器上部署了一个Scheduler,我们想在B服务器上控制这个Scheduler. 2. 猜想: A服务器上的Scheduler需要有 ...

  7. SpringBoot(七):SpringBoot整合Swagger2

    原文地址:https://blog.csdn.net/saytime/article/details/74937664 手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文 ...

  8. ORACLE使用CASE WHEN的方法

    先写草稿. 说下我的需求,ORACLE数据库有两个字段RECEIVER_MOBILE与RECEIVER_PHONE,同为联系方式.当RECEIVER_MOBILE为空的时候,需要用到RECEIVER_ ...

  9. java(10)类的无参方法

    一.变量的作用域(有效的使用范围) 1.变量有2种 1.1成员变量(属性) 声明在类的里面,方法的外面 1.2 局部变量 声明在方法里面或for循环结构中 2.调用时的注意事项(初始值不同.作用域不同 ...

  10. 2.10 while循环应用

    while循环应用 1. 计算1~100的累积和(包含1和100) 参考代码如下: #encoding=utf-8 i = 1 sum = 0 while i <= 100: sum = sum ...