網頁

2020/9/27

Spring Boot @PropertySource 依 spring.profiles.active載入對應的properties

Spring可在application.properties設定spring.profiles.active的值來切換不同環境用的application配置檔。而application外的自訂配置檔透過@PropertySource載入時也要依spring.profiles.active載入對應的配置檔的設定如下。


例如classpath src/main/resources有一自訂配置檔system-default.properites

system-defualt.properties

system.name=Demo system (Default)
system.url=192.168.0.111
system.port=8081

另外有開發環境(Dev)使用的system-dev.properties

system-dev.properties

system.name=Demo system (Dev)
system.url=192.168.0.112
system.port=8082

及正式環境(Prod)使用system-prod.properties

system-prod.properties

system.name=Demo system (Prod)
system.url=192.168.0.113
system.port=8083

@PropertySource指定配置檔來源時,可使用property placeholder${spring.profiles.active}帶入spring.profiles.active的值來切換要載入的properties。

DemoApplication

package com.abc.demo;

import com.abc.demo.properties.SystemProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;

@PropertySource("classpath:system-${spring.profiles.active}.properties") // 依spring.profiles.active載入對應的system-xxx.properties
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        SystemProperties systemProperties = ctx.getBean(SystemProperties.class);

        System.out.println(systemProperties.getName());
        System.out.println(systemProperties.getUrl());
        System.out.println(systemProperties.getPort());

    }

}

SystemPropertiessystem.properties綁定的bean類

SystemProperties

package com.abc.demo.properties;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@ConfigurationProperties(prefix = "system")
@Component
public class SystemProperties {

    private String name;    // system.name
    private String url;     // system.url
    private String port;    // system.port

}

啟動專案在DemoApplication.main()因出結果如下。

application.properties中設定spring.profiles.active=default則印出

Demo system (Default)
192.168.0.111
8081

spring.profiles.active=dev則印出

Demo system (Dev)
192.168.0.112
8082

spring.profiles.active=prod則印出

Demo system (Prod)
192.168.0.113
8083


參考github


沒有留言:

張貼留言