I'm trying to use an Enum to define the different profiles my Spring application might use.
This is my enum Profiles.java
public enum Profiles {
DEVELOPMENT("dev"),
TEST("test"),
PRODUCTION("prod");
private final String code;
private Profiles(String code) {
this.code = code;
}
}
I'm using it in a file to configure the properties place holders.
@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;
}
}
}
However it is complaining at @Profile that its getting incompatible types, got Profiles expected String. I feel like I'm missing something really silly.
Profile希望将String数组 (实现为varargs)作为其参数
@Profile(Profiles.DEVELOPMENT.name())
I think this will NOT work. I tried it in Java 8 and compiler complains that "Attribute value must be a constant".
As explained here it can only be primitive or String.
Possible solution is:
@Profile(SpringProfiles.TEST)
public static class SpringProfiles {
public static final String TEST = "test";
}
Even thought @Profile expects String[] this works - I guess there is some implicit conversion between String and String[].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.