自定义配置依赖,可引入可不引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

自定义属性配置

  • 通过注解注入

application.properties中定义属性:

my1.age=123
my1.name=zhangsan

通过属性注入


@value("${my1.age}")
private int age;

@value("${my1.name}")
private String name;
  • 通过定义class注入

application.properties中定义属性:

my2.age=123
my2.name=zhangsan

定义class类[MyProperties1]:


@Component
@ConfigurationProperties(prefix = "my1")
public class MyProperties1{

    private int age;
    private String name;

    public int getAge(){
        return this.age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }
}

自定义文件配置

添加自定义的属性配置文件[my3.properties]

my3.age=13
my3.name=liwu

定义class类[MyProperties2]:


@Component
@PropertySource("classpath:my3.properties")
@ConfigurationProperties(prefix = "my1")
public class MyProperties2{

    private int age;
    private String name;

    public int getAge(){
        return this.age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }
}

多环境化配置

常用的应用开发过程,一般都分为多套环境进行迭代开发。
SANDBOX环境、Dev环境、 ST2环境、PROD环境。
而每套环境的数据库、日志级别、缓存、消息中间件等参数的不同,可能每套环境都需要一套自定义的应用配置文件。

SpringBoot中支持多个配置文件,通过“spring.profiles.active=dev”和“application-{profile}.properties”来让那个环境属性文件生效。

例如: Dev环境[application-dev.properties]

server.servlet.context-path=/dev

ST2环境[application-st2.properties]

server.servlet.context-path=/st2

PROD环境[application-prod.properties]

server.servlet.context-path=/prod

外部命令引导

应用开发完成打包,通过jar命令启动服务时,可以通过参数追加来引导。
如:

java -jar chapter2-0.0.1-SNAPSHOT.jar --spring.profiles.active=test --my1.age=32
Copyright © wswzms.top 2019 all right reserved,powered by Gitbook该文件修订时间: 2019-04-17 14:15:33

results matching ""

    No results matching ""