簡體   English   中英

在Spring Boot Application初始化之前讀取屬性

[英]Reading a property before initialization of Spring Boot Application

我有這樣一種情況,從Spring程序運行之前從classpath:app.propertiesclasspath:presentation-api.properties讀取一個屬性,以設置幾個舊的配置文件,這將很有用。

所以會是這樣的:

@SpringBootApplication
@PropertySource({"classpath:app.properties", "classpath:various_other.properties"})
public class MainApp extends SpringBootServletInitializer {

   @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

        boolean legacyPropertyA = // might be set in classpath:app.properties or classpath:various_other.properties or not at all       
        boolean legacyPropertyB = // might be set in classpath:app.properties or classpath:various_other.properties or not at all

        if (legacyPropertyA) {
            builder.profiles("legacyProfileA");
        }
        if (legacyPropertyB) {
            builder.profiles("legacyProfileB");
        }

        return super.configure(builder);
    }
}

檢索legacyPropertyAlegacyPropertyB的最干凈方法是什么?

我認為您可以將@Value@PostConstruct批注結合起來,以獲得更清潔的解決方案。 請看下面的例子:

@SpringBootApplication
@PropertySource({"classpath:application-one.properties", "classpath:application-two.properties"})
public class MyApplication extends SpringBootServletInitializer {

    @Value("${property.one}")
    private String propertyOne;

    @Value("${property.two}")
    private String propertyTwo;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyApplication.class);
    }

    @PostConstruct
    public void initProperties() {
        System.out.println(propertyOne);
        System.out.println(propertyTwo);
    }
}

希望對您有所幫助。 請讓我知道您有任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM