Spring Boot 属于约定大于配置,就是说 Spring Boot 推荐不做配置,很多都是默认配置,但如果想要配置系统,使得软件符合业务定义,Spring Boot 可以通过多种方式进行配置。

Spring Boot 配置文件默认在 src/main/resouces/application.properties ,配置文件可以是 .properties 也可以是 .yml 后缀。两者除了展示形式,没有区别。

配置文件的三种方式

  1. bootstrap 开头 .properties 后缀 或 .yml 后缀,通常用于 Spring Cloud 应用
  2. application 开头 .properties 后缀 或 .yml 后缀,每个 Spring Boot 应用默认
  3. 通过 @Configuration 注解的代码类配置
  4. 通过 cmd 命令行配置

1 bootstrap

1.1 bootstrap 应用场景

因为本系列是 Spring Boot 教程实例,没有设计到 Spring Cloud ,而 Bootstrap 实际应用场景是在 Spring Cloud,本章也不具体讨论。

1.2 bootstrap 与 application

bootstrap.yml(bootstrap.properties)用来程序引导时执行,应用于更加早期配置信息读取,如可以使用来配置application.yml中使用到参数等。

application.yml(application.properties) 应用程序特有配置信息,可以用来配置后续各个模块中需使用的公共参数等。

bootstrap.yml 先于 application.yml 加载

为什么要有 bootstrap 配置

2 application

application.yml(application.properties) 是针对独立 Spring Boot 的应用配置文件,跟 .NET 的 web.confg(app.confg) 文件功能一样。

2.1 application 常用配配置

2.1.1 端口配置

properties 格式

#指定springboot内嵌容器启动的端口,默认使用tomcat容器时在8080端口
server.port=8081

yml 格式

#指定springboot内嵌容器启动的端口,默认使用tomcat容器时在8080端口
server
port: 8081

2.1.2 thymeleaf组件配置

properties 格式

#是否开启thymeleaf缓存
spring.thymeleaf.cache=false
#thymeleaf路径
spring.thymeleaf.prefix=classpath:/templates/
#后缀
spring.thymeleaf.suffix=.html
#编码
spring.thymeleaf.encoding=UTF-8
#文本类型
spring.thymeleaf.content-type=text/html
#展示形式
spring.thymeleaf.mode=HTML5

yml 格式

#thymelea模板配置
spring:
thymeleaf:
#缓存
cache: false
#thymeleaf 所在路径
prefix: classpath:/templates/
#thymeleaf 后缀
suffix: .html
#thymeleaf 采用的标准
mode: HTML5
#thymeleaf 编码格式
encoding: UTF-8

2.1.3 数据库连接配置

properties 格式

#描述数据源 #编码、时区等格式
spring.datasource.url=jdbc:mysql://localhost:3306/tanglong?useUnicode=true&
characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia
#数据源用户名
spring.datasource.username=root
#数据源密码
spring.datasource.password=0000
#数据源驱动包名
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
#数据源类型
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource

2.1.4 数据持久化

#是否打印sql语句
spring.jpa.show-sql= true
#mybatis配置文件路径
mybatis.config-location=classpath:MyBatis.xml
#指定 mybatis 本地路径,例如在 mybatis/mappings 下所有的 xml 后缀的文件
mybatis.mapper-locaitons=classpath:mybatis/mappings/*.xml
#打印myBatis的sql语句 com.demo.mapper 为包名
logging.level.com.demo.mapper=debug
#别名实体包,多个逗号隔开
mybatis.type-aliases-package=com.user.bean

2.1.5 多种开发环境

多环境配置请参见 Spring Boot 多环境如何配置

#开发/测试/生产环境分别对应dev/test/prod,可以自由定义,当前配置为开发环境
spring.profiles.active=dev #不同环境中的配置信息可以写在其他文件中
application-test.properties 或者 application-prod.properties

2.2 如何获取 application 中的值

2.2.1 新建一个类标注 @ConfigurationProperties

  1. 新建一个 java 类
  2. 给类加 @ConfigurationProperties(prefix = "corn") 其中 prefix 表前缀,例如 corn.username=123,那么corn就是前缀

    假设 application.yml 代码如下
corn:
uploadPath: /Users/jiaojunkang/Documents/project_java/corn/src/corn-master/files/
rootPath: /Users/jiaojunkang/Documents/project_java/fwrsoft/html/
host: corn.icontag.cn
componentAppId:
componentSecret:
componentToken:
componentAesKey:
baiduApikey:
baiduSecretkey:
baiduAppId:
smsUrl:
smsUid:
smsPwd:
pageSize: 10

那么对应的 java 配置类


@Component
@ConfigurationProperties(prefix = "corn")
public class CornConfig {
//上传路径
private String uploadPath; //静态文件跟目录
private String rootPath; //HOST
private String host;
//微信开发平台appid
private String componentAppId;
private String componentSecret;
private String componentToken;
private String componentAesKey; private String baiduApikey;
private String baiduSecretkey; private String smsUrl; private String pageSize; public String getPageSize() {
return pageSize;
} public void setPageSize(String pageSize) {
this.pageSize = pageSize;
} public String getSmsUrl() {
return smsUrl;
} public void setSmsUrl(String smsUrl) {
this.smsUrl = smsUrl;
} public String getSmsUid() {
return smsUid;
} public void setSmsUid(String smsUid) {
this.smsUid = smsUid;
} public String getSmsPwd() {
return smsPwd;
} public void setSmsPwd(String smsPwd) {
this.smsPwd = smsPwd;
} private String smsUid; private String smsPwd; public String getBaiduAppId() {
return baiduAppId;
} public void setBaiduAppId(String baiduAppId) {
this.baiduAppId = baiduAppId;
} private String baiduAppId; public String getUploadPath() {
return uploadPath;
} public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
} public String getRootPath() {
return rootPath;
} public void setRootPath(String rootPath) {
this.rootPath = rootPath;
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public String getComponentAppId() {
return componentAppId;
} public void setComponentAppId(String componentAppId) {
this.componentAppId = componentAppId;
} public String getComponentSecret() {
return componentSecret;
} public void setComponentSecret(String componentSecret) {
this.componentSecret = componentSecret;
} public String getComponentToken() {
return componentToken;
} public void setComponentToken(String componentToken) {
this.componentToken = componentToken;
} public String getComponentAesKey() {
return componentAesKey;
} public void setComponentAesKey(String componentAesKey) {
this.componentAesKey = componentAesKey;
} public String getBaiduApikey() {
return baiduApikey;
} public void setBaiduApikey(String baiduApikey) {
this.baiduApikey = baiduApikey;
} public String getBaiduSecretkey() {
return baiduSecretkey;
} public void setBaiduSecretkey(String baiduSecretkey) {
this.baiduSecretkey = baiduSecretkey;
}
}

2.2.2 在普通的类中使用 value 配置

给属性增加 @Value 标签,例如 使用 @Value("${spring.redis.host}") 标注 host 表示 Redis

@Value("${spring.redis.host}")
private String host = "127.0.0.1"; @Value("${spring.redis.port}")
private int port = 6379; // 0 - never expire
private int expire = 0; //timeout for jedis try to connect to redis server, not expire time! In milliseconds
@Value("${spring.redis.timeout}")
private int timeout = 0; @Value("${spring.redis.password}")
private String password = "";

3 @Configuration

使用 @Configuration 也可以替代部分 application.yml 文件配置,但 @Configuration 可以更加灵活的实现配置的自定义,他们的区别或者在于 @Configuration 可以动态配置,缺点是一旦发布无法更改。

  1. @Configuration 通常用于 aplication的补充
  2. @Configuration 用在类上,@Bean 用在方法上

例如配置 QuartzConfigration 通常采用的配置


@Configuration
public class QuartzConfigration {
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/config/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
} // 创建schedule
@Bean(name = "scheduler")
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}

4 命令行配置

Spring Boot 在服务器部署可以使用下面命令,这时使用 -- 开头引入 spring 中的 application 的值,即可在命令行配置 Spring Boot。

java -jar xxxx-0.0.1-SNAPSHOT.jar

我们可以通过在命令行增加配置的方式给 Spring Boot 添加配置,命令行配置优先于 application.yml 执行。

如下配置了一个端口,使用 --server.port=8088 配置 来实现命令行配置

java -jar xxxx-0.0.1-SNAPSHOT.jar --server.port=8088 --spring.profiles.active=dev

Spring Boot 配置文件和命令行配置的更多相关文章

  1. Spring Boot程序接收命令行参数

    Spring Boot程序接收命令行参数 输入一行,回车,触发一次.如果想要调用service层,也是可以,能调用service层,就可以做很多事,触发一次就好比调用了一次http接口一样 packa ...

  2. Spring boot 配置文件参数映射到配置类属性

    [参考文章]:SpringBoot之@EnableConfigurationProperties分析 [参考文章]:在Spring Boot中使用 @ConfigurationProperties 注 ...

  3. Spring Boot配置文件yml讲解--行内对象的配置方式

    yml行内对象的配置方法,一般是采取 上面的缩进方式,我只想配置在一行怎么处?——

  4. 详解Spring Boot配置文件之多环境配置

    一. 多环境配置的好处: 1.不同环境配置可以配置不同的参数~ 2.便于部署,提高效率,减少出错~ 二. properties多环境配置 1. 配置激活选项 spring.profiles.activ ...

  5. Spring Boot 配置文件 – 在坑中实践

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 仓廪实而知礼节,衣食足而知荣辱 - 管仲 』   本文提纲 一.自动配置 二.自定义 ...

  6. Springboot 系列(二)Spring Boot 配置文件

    注意:本 Spring Boot 系列文章基于 Spring Boot 版本 v2.1.1.RELEASE 进行学习分析,版本不同可能会有细微差别. 前言 不管是通过官方提供的方式获取 Spring ...

  7. Spring Boot 启动(二) 配置详解

    Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...

  8. 史上最全的Spring Boot配置文件详解

    Spring Boot在工作中是用到的越来越广泛了,简单方便,有了它,效率提高不知道多少倍.Spring Boot配置文件对Spring Boot来说就是入门和基础,经常会用到,所以写下做个总结以便日 ...

  9. Spring Boot 配置文件中的花样,看这一篇足矣!

    在快速入门一节中,我们轻松的实现了一个简单的RESTful API应用,体验了一下Spring Boot给我们带来的诸多优点,我们用非常少的代码量就成功的实现了一个Web应用,这是传统的Spring应 ...

随机推荐

  1. 源码解读 Spring Boot Profiles

    前言 上文<一文掌握 Spring Boot Profiles> 是对 Spring Boot Profiles 的介绍和使用,因此本文将从源码角度探究 Spring Boot Profi ...

  2. 阿里云短信服务(JAVA)

    一,前言 ​ 短信验证码想必大家都不陌生,在很多网站,APP中都有使用到.比如登录,注册,身份校验等场景.不过通常情况下,短信服务都是外包给第三方公司的,接下来向大家分享如何使用阿里的短信服务. 二, ...

  3. 走进JavaWeb技术世界5:初探Tomcat的HTTP请求过程

    初探Tomcat的HTTP请求过程 前言:1.作为Java开发人员,大多都对Tomcat不陌生,由Apache基金会提供技术支持与维护,因为其免费开源且易用,作为Web服务器深受市场欢迎,所以有必要对 ...

  4. java后端_百度二面

    参考: https://www.nowcoder.com/discuss/215891?type=2&order=0&pos=10&page=1 1. gc 2. java l ...

  5. Socket通信封装MIna框架--含羞代放

    目录 核心类 各个击破 IoService IoFilter IoHandler 总结 # 加入战队 微信公众号 Mina异步IO使用的Java底层JNI框架,Mina提供服务端和客户端,将我们的业务 ...

  6. pak文件的打包和解包

    pak格式的文件 一般游戏有资源 游戏素材会打包放进去 比如游戏语音 游戏多加点语音  多加一些贴图资源 外部文件实现的 素材--->pak文件--->用的时候从文件中取出来 文件的打包 ...

  7. python实现RSA加密和签名以及分段加解密的方案

    1.前言 很多朋友在工作中,会遇到一些接口使用RSA加密和签名来处理的请求参数,那么遇到这个问题的时候,第一时间当然是找开发要加解密的方法,但是开发给加解密代码,大多数情况都是java,c++,js等 ...

  8. HBase 系列(五)——HBase 常用 Shell 命令

    一.基本命令 打开 Hbase Shell: # hbase shell 1.1 获取帮助 # 获取帮助 help # 获取命令的详细信息 help 'status' 1.2 查看服务器状态 stat ...

  9. mybatis嵌套map或者map嵌套的parameterType

    Spring的重要注解 https://www.cnblogs.com/rolandlee/p/11014923.html 一:首先是map嵌套: 例1: 例2: 总结: paramterType无论 ...

  10. Django之ORM-model模型关系

    模型类关系 1)一对多关系例:图书类-英雄类 models.ForeignKey() 定义在多的类中. 2)多对多关系例:新闻类-新闻类型类 体育新闻 国际新闻models.ManyToManyFie ...