深入理解SpringBoot配置
一、application.properties的位置
1.当前目录的 “/config”的子目录下
2.当前目录下
3.classpath根目录的“/config”包下
4.classpath的根目录下
spring会从classpath下的/config目录或者classpath的根目录查找application.properties或application.yml。
/config优先于classpath根目录
说明:
- 1,2两项适合生产环境,可以直接跟jar包放在同级目录下
- 如果同时在四个地方都有配置文件,配置文件的优先级是从1到4。
- 使用配置文件之后,spring boo启动时,会自动把配置信息读取到spring容器中,并覆盖spring boot的默认配置
SpringBoot的配置方式有很多,它们的优先级如下所示(优先级递减顺序):
- 命令行参数
- 来自java:comp/env的JNDI属性
- Java系统属性(System.getProperties())
- 操作系统环境变量
- RandomValuePropertySource配置的random.*属性值
- jar包外部的
application-{profile}.properties或application.yml(带spring.profile)配置文件 - jar包内部的
application-{profile}.properties或application.yml(带spring.profile)配置文件 - jar包外部的
application.properties或application.yml(不带spring.profile)配置文件 - jar包内部的
application.properties或application.yml(不带spring.profile)配置文件 @Configuration注解类上的@PropertySource- 通过
SpringApplication.setDefaultProperties指定的默认属性
因为jar包外部的优先级高,所以可以运行时指定application.properties的位置。
以上配置方式虽然挺多,实际用到的只有一两种。
二、 通过命令行来配置少量项
SpringBoot可以不依赖Tomcat容器,作为单应用启动。这时,可以通过命令行来控制运行参数。
通过命令行来重写和配置环境变量,优先级最高,例如可以通过下面的命令来重写spring boot 内嵌tomcat的服务端口,注意“=”俩边不要有空格
java -jar demo.jar --server.port=9000
如果想要设置多个变量怎么办,可以用json的格式字符串来设置
java -jar demo.jar --spring.application.json='{"foo":"bar"}'
三、 使用@Value注解
@RestController
@RequestMapping("/task")
public class TaskController {
@Value("${connection.remoteAddress}") private String address;
@RequestMapping(value = {"/",""})
public String hellTask(@Value("${connection.username}")String name){
return "hello task !!";
}
}
@Value注解有好几种姿势:
1. #{expression?:default value}
@Value("#{systemProjecties['mongodb.port']?:27017}")
private String mongodbPort;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
@Value("#{aBean.age ?:21}")
private int age;
2. ${property:default value}
//@propertySource("classpath:/config.properties")
//configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongoUrl;
@Value("#config['mongodb.url']?:'127.0.0.1'")
private String mogodbUrl;
配置文件config.property如下:
mogodb.url = 1.2.3.4
mogodb.db = hello
3. 注意
Must register a static PropertySourcesPlaceholderConfiger bean in either XML or annotation ,so that Spring @Value konw how to interpret ${}
//@PropertySource("classpath:/config.properties}")
//@Configuration
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
四、 属性的引用
myapp.name=spring
myapp.desc=${myapp.name} nice
SpringBoot提供以下特殊引用:
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
五、 自定义配置信息
@Component
public class SystemConfig {
private static Properties props ;
public SystemConfig(){
try {
Resource resource = new ClassPathResource("/application.properties");//
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取属性
* @param key
* @return
*/
public static String getProperty(String key){
return props == null ? null : props.getProperty(key);
}
/**
* 获取属性
* @param key 属性key
* @param defaultValue 属性value
* @return
*/
public static String getProperty(String key,String defaultValue){
return props == null ? null : props.getProperty(key, defaultValue);
}
/**
* 获取properyies属性
* @return
*/
public static Properties getProperties(){
return props;
}
}
//用的话,就直接这样子
String value = SystemConfig.getProperty("key");
六、SpringBoot自带的配置属性
常用属性如日志,端口配置
# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)
# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'
更多属性参见官网文档
@ContextConfiguration
@ContextConfiguration(locations={"classpath*:mongodb.xml"})
七、属性名匹配规则
例如有如下配置对象:
@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {
private String firstName;
}
firstName可以使用的属性名如下:
person.firstName,标准的驼峰式命名
person.first-name,虚线(-)分割方式,推荐在.properties和.yml配置文件中使用
PERSON_FIRST_NAME,大写下划线形式,建议在系统环境变量中使用
参考资料
深入理解SpringBoot配置的更多相关文章
- SpringBoot配置Aop笔记【例子】
众所周知,spring最核心的两个功能是aop和ioc,即面向切面,控制反转.这里我们探讨一下如何使用spring aop. 1.何为aop aop全称Aspect Oriented Programm ...
- SpringBoot 配置 Tomcat SSL
SpringBoot 配置 Tomcat SSL SSL(Secure Sockets Layer , 安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密 ...
- 深入理解SpringBoot核心机制《spring-boot-starter》
深入理解SpringBoot核心机制<spring-boot-starter> 前言: 对于这几年java火爆天的springBoot我相信大家都有所使用过,在springBoot的项目中 ...
- SpringBoot配置属性之Server
SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...
- Nginx模块开发-理解HTTP配置
理解HTTP配置 相关数据结构 先明白Nginx下述数据结构,再理解 HTTP配置的解析与合并过程 ngx_module_t 官方API typedef struct{ NGX_MODULE_V1; ...
- SpringBoot基础系列-SpringBoot配置
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9990680.html SpringBoot基础系列-SpringBoot配置 概述 属性 ...
- springboot上传文件 & 不配置虚拟路径访问服务器图片 & springboot配置日期的格式化方式 & Springboot配置日期转换器
1. Springboot上传文件 springboot的文件上传不用配置拦截器,其上传方法与SpringMVC一样 @RequestMapping("/uploadPicture&q ...
- springboot配置Druid数据源
springboot配置druid数据源 Author:SimpleWu springboot整合篇 前言 对于数据访问层,无论是Sql还是NoSql,SpringBoot默认采用整合SpringDa ...
- springboot配置详解
springboot配置详解 Author:SimpleWu properteis文件属性参考大全 springboot默认加载配置 SpringBoot使用两种全局的配置文件,全局配置文件可以对一些 ...
随机推荐
- MySQL冷知识
问题:在网站后台添加了扩展字段后,对于数据库表不太熟悉的,可能会花较长时间查找,如何有效提高我们的工作效率呢? 解决方法:利用SQL语句来查询字段所在的表
- crtmpserver实现防盗流和流推送验证 之二
IV. Catching the thieves 抓住小偷 Well, we have just added a secure mechanism to our little streaming se ...
- 使用Spring Security和OAuth2实现RESTful服务安全认证
这篇教程是展示如何设置一个OAuth2服务来保护REST资源. 源代码下载github. (https://github.com/iainporter/oauth2-provider)你能下载这个源码 ...
- jquery圆角插件
为了实现div的圆角效果,你还在用古老的背景图片拼凑的方法吗?还是在用各种浏览器不互相兼容的CSS方式?如果你还在用这样的方式实现圆角,那我告诉你你真的out了,或许是我out了,竟然以前没发现有这样 ...
- 提高你开发效率的十五个 Visual Studio 使用技巧
相信做开发的没有不重视效率的.开发C#,VB的都知道,我们很依赖VS,或者说,我们很感谢VS.能够对一个IDE产生依赖,说明这个IDE确实 有它的独特之处.无容置疑,VS是一个非常强大的IDE,它支持 ...
- IOS基本数据类型之枚举
枚举是C语言中的一种基本数据类型,通过枚举可以声明一组常数,来代表不同的含义,它实际上就是一组整型常量的集合. 枚举是非常常用的一种类型,在现实生活中也很常见.比如有四个季节,在不同的季节需要显示不同 ...
- 向量的表示及协方差矩阵 (PCA的理论基础)
原文:http://blog.csdn.net/songzitea/article/details/18219237 引言 当面对的数据被抽象为一组向量,那么有必要研究一些向量的数学性质.而这些数学性 ...
- python 初步学习
疑惑1:windows下的python 如何设置显示汉字 推荐几个学习网址,也方便自己以后查看: http://pmghong.blog.51cto.com/3221425/d-10 www.w3c ...
- TCP/IP、SOCKET、HTTP之间的联系与区别
主要内容: 1.网络的七层协议 2.TCP/IP.SOCKET.HTTP简介 3.TCP连接.HTTP连接.Socket连接的区别 一.网络的七层协议 网络七层由下往上分别为物理层.数据链路层.网络层 ...
- hadoop2.2.0_hbase0.96_zookeeper3.4.5全分布式安装文档下载
本文档主要内容有: 1.hadoop 2.2.0 集群安装与部署 2.HBase 0.96 集群安装与部署 3.Zookeeper 3.4.5集群安装部署 备注:安装文档可能有所遗漏,后续将持续更新. ...