使用 java 配置将属性单独存储在 Spring 应用中的 Web 项目之外

Store properties separately outside the web project in Spring app using java config

我想在 Tomcat 服务器中保留属性。我想初始化一些 bean 用于开发,一些用于生产。什么是最好的解决方案?

我尝试使用 Condition 接口,但收到 NullPointerException。看来我没有从我的 属性 中获得价值。我做错了什么?

我将 属性 文件放在 /home/user/apache-tomcat-home-dir/conf/my.属性 并添加

 <Environment name="my_config" value="file:///${catalina.home}/conf/my.properties" type="java.net.URI"/>

/home/user/apache-tomcat-home-dir/conf/context.xml

my.properties只有一个属性:

profiler.default=dev

这就是我在项目中使用 属性 的方式:

public class ProductionCondition implements Condition {

    @Value("${profiler.default}")
    private String prodProfiler;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return prodProfiler.equals("production");
    }
}

public class DevCondition implements Condition {

    @Value("${profiler.default}")
    private String coreProfiler;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//        return coreProfiler.equals("dev");
        return context.getEnvironment().getProperty("profiler.default").contains("dev");
    }
}

我应该配置 PropertySourcesPlaceholderConfigurer 以从文件初始化属性:

@Configuration(value = "propertiesConfiguration")
@PropertySource(value="file:${catalina.home}/conf/my.properties")
public class PropertiesConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() throws MalformedURLException {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
//        configurer.setLocation(new FileSystemResource(propertyFile));
        return configurer;
    }
}

什么是正确的形式:${catalina.home}${catalina/home} 或如何指定我的 属性 文件的相对路径?

在配置 class 中,我初始化条件 bean 并指定此配置 class 取决于 PropertiesConfiguration。

@Configuration
@Import({PropertiesConfiguration.class})
@DependsOn("propertiesConfiguration")
public class ApplicationConfig {

    @Bean
    @Conditional(ProductionCondition.class)
    public FooInterface productionVendorCore() {
        return new ProductionImpl();
    }

    @Bean
    @Conditional(DevCondition.class)
    public FooInterface devVendorCore() {
        return new DevImpl();
    }
//....
}

但无论如何我在 ProductionCondition 中收到 NPE:

return prodProfiler.equals("production");

感谢任何帮助!

与其尝试发明自己的轮子,不如尝试使用已经提供的轮子。请改用 profiles

在您的 tomcat 中,只需将 SPRING_PROFILES_ACTIVE 属性 添加到 jndi 中,并使用您想要的值 productiondev。或者你可以设置成环境或者jvm 属性.

<Environment name="SPRING_PROFILES_ACTIVE" value="production" type="java.lang.String"/>

然后使用 @Profile 注释您的 bean 定义并为某些配置文件启用它们。

public class ApplicationConfig {

    @Bean
    @Profile("production")
    public FooInterface productionVendorCore() {
        return new ProductionImpl();
    }

    @Bean
    @Profile("dev")
    public FooInterface devVendorCore() {
        return new DevImpl();
    }
    //....
}

这应该只加载已启用配置文件中的 bean。无需您进行任何额外的工作。