使用ENUM进行配置文件,但期望一个字符串

时间:2015-03-23 23:21:22

标签: java spring enums

我尝试使用Enum来定义Spring应用程序可能使用的不同配置文件。

这是我的枚举Profiles.java

public enum Profiles {

    DEVELOPMENT("dev"),
    TEST("test"),
    PRODUCTION("prod");

    private final String code;

    private Profiles(String code) {
        this.code = code;
    }
}

我在文件中使用它来配置属性占位符。

@Configuration
public class PropertyPlaceholderConfig {

    @Profile(Profiles.DEVELOPMENT)
    public static class DevelopmentConfig {
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
            PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
            propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
            propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("props/application-dev.properties"));
            return propertySourcesPlaceholderConfigurer;
        }
    }

    @Profile(Profiles.TEST)
    public static class TestConfig {
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
            PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
            propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
            propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("props/application-test.properties"));
            return propertySourcesPlaceholderConfigurer;
        }
    }

    @Profile(Profiles.PRODUCTION)
    public static class ProductionConfig {
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
            PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
            propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
            propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application-test.properties"));
            return propertySourcesPlaceholderConfigurer;
        }
    }
}

然而,它正在@Profile抱怨其获得不兼容的类型,得到了Profiles期望的String。我觉得我错过了一些非常愚蠢的东西。

2 个答案:

答案 0 :(得分:1)

配置文件需要String array(实现为varargs)作为其参数

@Profile(Profiles.DEVELOPMENT.name())

答案 1 :(得分:1)

我认为这不起作用。我在Java 8中尝试过,编译器抱怨“属性值必须是常量”。

正如here所解释的那样,它只能是原始的或字符串。

可能的解决方案是:

@Profile(SpringProfiles.TEST)
public static class SpringProfiles {
    public static final String TEST = "test"; 

}

甚至认为@Profile期望String []这个有效 - 我猜在String和String []之间存在一些隐式转换。