Springboot-23高级特性(profile、加载优先级、自定义starter)

1、profile

(1)环境切换

#1、环境配置
spring:
  #当前环境
  profiles:
    active: dev

在这里插入图片描述

  • 默认配置文件与环境配置同时存在某个配置项,环境配置优先加载;
  • 打包之后可以重新选择环境激活,使用如下指令:
java -jar xxx.jar --spring.profiles.active=prod  --person.name=haha

–spring.profiles.active=prod:重新制定配置文件;
–person.name=haha:重新制定配置属性;

(2)条件装配

常见配置装配方式:

  • @value("{person.name:李四}") //属性值:表示找不到当前属性,默认值为李四
  • @ConfigurationProperties("person") //自动绑定
@Component //放入容器
@ConfigurationProperties("person")
@Profile("production")
public class Person{
    public String name;
    public int age;
}

配置内容在这里插入图片描述

常见:开发环境与生产环境同时存在person对象,它们具有相同的属性,但是开发环境person是个student属性,生产环境是个teacher属性,此时可以通过@Profile注解指定环境,让配置生效,,既可以使用在类上,也可以使用在方法上。

@Component //放入容器
@ConfigurationProperties("person")
@Profile("dev") //测试环境才会绑定生效
public class Person{
    public String name;
    public int age;
}

(3)分组

spring.profiles.group.production[0]=pro1 #生产1组name属性
spring.profiles.group.production[1]=pro2 #生产2组age属性

使用:–spring.profiles.active=production 激活完整person信息

2、外部化配置

官网介绍

(1)配置项位置来源

  • Java属性文件、YAML文件、环境变量、命令行参数;
1. Default properties (specified by setting SpringApplication.setDefaultProperties).
2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
3. Config data (such as application.properties files)
4. A RandomValuePropertySource that has properties only in random.*.
5. OS environment variables.
6. Java System properties (System.getProperties()).
7. JNDI attributes from java:comp/env.
8. ServletContext init parameters.
9. ServletConfig init parameters.
10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
11. Command line arguments.
12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
13. @TestPropertySource annotations on your tests.
14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

(2)配置文件查找位置

  • classpath 根路径
  • classpath 根路径下config目录
  • jar包当前目录
  • jar包当前目录的config目录
  • /config子目录的直接子目录

(3)规则
指定环境优先,外部优先,后面的可以覆盖前面的同名配置项。

3、starter启动器

(1)原理
自定义一个starter,引入autoconfigure,再引入底层spring-boot-starter

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值