繁体   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