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. Scanner和BufferReader的效率问题

    先给出一道题,测试平台是Acwing, 这道题是腾讯2019年春招提前批笔试第二题.题目不难,但是如果不注意细节,很容易TLE(超时) https://www.acwing.com/problem/c ...

  2. 对Datatable中过长内容实行省略话

    , 16) + '...</a>' } // 点击跳转的实现 else { return '<a id="taskFocus" href="/task_ ...

  3. redis哨兵(Sentinel)、虚拟槽分区(cluster)和docker入门

    一.Redis-Sentinel(哨兵) 1.介绍 Redis-Sentinel是redis官方推荐的高可用性解决方案,当用redis作master-slave的高可用时,如果master本身宕机,r ...

  4. 后缀自动机(SAM)学习笔记

    目录 定义 SAM 的状态集 一些性质 SAM 的后缀链接 SAM 的转移函数 一些性质 算法构造 构造方法 时间复杂度证明 状态的数量 转移的数量 代码实现 实际应用 统计本质不同的子串个数 计算任 ...

  5. (转)Spring事务管理详解

    背景:之前一直在学习数据库中的相关事务,而忽略了spring中的事务配置,在阿里面试时候基本是惨败,这里做一个总结. 可能是最漂亮的Spring事务管理详解 https://github.com/Sn ...

  6. GWAS文献解读:The stability of educational achievement across school years is largely explained by genetic factors

    方法 从NPD(英国数据库,收集有关学生在学年中学业成绩的数据)和TEDS(英国国家课程指南报告成绩数据库,由国家教育研究基金会和资格与课程管理局制定标准化核心学术课程)数据库获得双胞胎的学业成绩数据 ...

  7. Numpy系列(六)- 形状操作

    Numpy 有一个强大之处在于可以很方便的修改生成的N维数组的形状. 更改数组形状 数组具有由沿着每个轴的元素数量给出的形状: a = np.floor(10*np.random.random((3, ...

  8. Python 文件行数读取的三种方法

    Python三种文件行数读取的方法: #文件比较小 count = len(open(r"d:\lines_test.txt",'rU').readlines()) print c ...

  9. Docker:私有仓库registry [十一]

    一.运行docker私有仓库 安装registry docker run -d -p 5000:5000 --restart=always --name registry -v /opt/myregi ...

  10. 一个select元素自定义设计的新思路:appearance: none之后利用<>符号制造小箭头

    最近工作时解决了一个前端小问题(如下图所示):在Safari中,select的控件之上有不和谐的灰色部分. 刚开始时我以为是backgrand或是border设置不当之类产生的问题,在搜索了很久之后终 ...