配置文件application .yml
YAML 是专门用来写配置文件的语言。springboot中可添加如下配置文件
application.yml
application-dev.yml
application-pro.yml
注意:冒号后面要加空格,这样spring boot 才能识别
系统环境变量里如果有配置属性PROFILE,会读取环境变量的值
spring:
profiles:
active: ${PROFILE:dev}
http:
encoding:
force: true
server:
port: 8080
management:
security:
enabled: false #关掉安全认证
port: 8088 #管理端口调整成8088
context-path: /monitor #actuator的访问路径
endpoints:
shutdown:
enabled: true
application-dev.yml
product:
name: stark
nickName: s
在类中可用如下方式读取配置值
@Data
@Component
public class Product{
@Value("${product.name}")
private String name;
@Value("${product.nickName}")
private String nickName;
}
使用Product对象需要使用@Autowired、@Resource引入
通过命令行配置属性
命令:java -jar xxx.jar --server.port=8888,通过使用–server.port属性来设置xxx.jar应用的端口为8888
两个减号–就是对application.properties中的属性值进行赋值的标识
安全起见,Spring Boot提供了屏蔽命令行访问属性的设置,只需要这句设置就能屏蔽:SpringApplication.setAddCommandLineProperties(false)。
配置优先级
- 命令行参数
- 来自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指定的默认属性