首页 > 解决方案 > 在 Spring Boot 应用程序初始化之前读取属性

问题描述

我有一种情况,在运行 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);
    }
}

legacyPropertyA检索和的最干净的方法是legacyPropertyB什么?

标签: javaspringspring-bootinitialization

解决方案


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

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


推荐阅读