在初始化Spring Boot Application之前读取属性

时间:2018-05-02 13:41:31

标签: java spring spring-boot initialization

我的情况是,在运行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的最简洁方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为您可以将 @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);
    }
}

我希望这可以帮到你。请让我知道你有任何问题。