Spring Boot学习,配置文件占位符和多环境支持

配置文件占位符和多环境支持

  • 配置文件占位符
    • RandomValuePropertySource
    • 属性配置占位符
  • 多环境支持(profile)
    • profile文件的写法
  • 激活指定profile

配置文件占位符

RandomValuePropertySource

配置文件可以使用Spring Boot 提供的一些随机数,如:

${random.value}, ${random.int}, ${random.long}, ${random.int(10)}, ${random.int(1024,1256)}

属性配置占位符

可以在配置文件中引用前面配置过的属性,如果引用的属性没有,还可以设置默认值,如果没有写默认值又没有定义,那么就会将表达式当成字符串输出。如:

app.name=MyApp
app.description=${app.name} is a Spring Boot Application.
app.desc=${app.version:v1.0} is current version

实体:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
 * @ClassName Person
 * @Date 2019/7/11 16:57
 * @Description
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String surname;
    private String name;
    private Integer age;
    private Date birth;
    private boolean boss;
    private String say;
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public boolean isBoss() {
        return boss;
    }
    public void setBoss(boolean boss) {
        this.boss = boss;
    }
    public String getSay() {
        return say;
    }
    public void setSay(String say) {
        this.say = say;
    }
    @Override
    public String toString() {
        return "Person{" +
                "surname='" + surname + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                ", boss=" + boss +
                ", say='" + say + '\'' +
                '}';
    }
    public void sayHi() {
        System.out.println(say);
    }
}

yml配置文件:

person:
  surname:name: 三${random.uuid} # 使用随机的UUID
  age: ${random.int} # 随机的int
  boss: false
  birth: 2019/7/12
  # 获取之前配置的surname、name、pet.type和pet.name属性,pet.type:没有配置,设置了默认值,pet.name:没有设置默认值
  say: ${person.surname}先生名叫${person.name},有一个宠物是${pet.type:},叫做${pet.name}.

测试:

@Autowired
Person person;
@Test
    public void contextLoads() {
        System.out.println(person);
        person.sayHi();
    }

结果

Person{surname='张', name='三679487a1-30c7-4958-9b9e-ae52751be909', age=1640749302, birth=Fri Jul 12 00:00:00 CST 2019, boss=false, say='张先生名叫三a8a96ed5-409b-40cf-9aad-13322b36192b,有一个宠物是狗,叫做${pet.name}.'}
张先生名叫三a8a96ed5-409b-40cf-9aad-13322b36192b,有一个宠物是狗,叫做${pet.name}.

多环境支持(profile)

profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、知道参数等方法快速切换环境。

profile文件的写法

  1. 多profile文件
    文件名:application-{profile}.properties/yml,如application-dev.properties。默认使用的是application.properties

  2. yml多文档块
    yml 有一种叫文档块,用’—'分割,如

server:
  port: 8081
spring:
  profiles:
    active: prod
---
server:
  port: 8082

spring:
  profiles: dev
---
server:
  port: 8083

spring:
  profiles: prod

激活指定profile

  1. 在默认配置文件(application.properties)中指定,如:
# properties
spring.profiles.active=dev
# yml
spring:
  profiles:
    active: dev
  1. 命令行的方式
--spring.profiles.active=dev


// cmd 命令行
E:\jl_whw\private\git_repository\springboot\springbootconfigpropertysource\target>java -jar spring-boot-config-property-source-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-12 15:42:22.731  INFO 2840 --- [           main] pringBootConfigPropertySourceApplication : Starting SpringBootConfigPropertySourceApplication v0.0.1-SNAPSHOT on DESKTOP-O1S9VQ2 with PID 2840 (E:\jl_whw\private\git_repository\springboot\springbootconfigpropertysource\target\spring-boot-config-property-source-0.0.1-SNAPSHOT.jar started by JL_Computer in E:\jl_whw\private\git_repository\springboot\springbootconfigpropertysource\target)
2019-07-12 15:42:22.735  INFO 2840 --- [           main] pringBootConfigPropertySourceApplication : The following profiles are active: prod
2019-07-12 15:42:24.379  INFO 2840 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8083 (http)
2019-07-12 15:42:24.415  INFO 2840 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-12 15:42:24.415  INFO 2840 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-12 15:42:24.555  INFO 2840 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-12 15:42:24.555  INFO 2840 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1741 ms
组件添加成功!!!
2019-07-12 15:42:24.815  INFO 2840 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-12 15:42:25.055  INFO 2840 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8083 (http) with context path ''
2019-07-12 15:42:25.060  INFO 2840 --- [           main] pringBootConfigPropertySourceApplication : Started SpringBootConfigPropertySourceApplication in 2.887 seconds (JVM running for 3.505)
  1. 虚拟机参数
-Dspring.profiles.active=dev

用IDEA测试控制台和虚拟机参数:
Spring Boot学习,配置文件占位符和多环境支持_第1张图片

你可能感兴趣的:(SpringBoot)