mardi 31 mars 2015

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

I want to hold properties in Tomcat server. I want initialize some bean for development and some for production. What is the best solution?


I tried to use Condition interface, but I receive NullPointerException. It seams that I didn't receive value from my property. What I'm doing wrong?


I place my property file in /home/user/apache-tomcat-home-dir/conf/my.properties and add



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


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


In my.properties only one property:



profiler.default=dev


And that's how I use my property in project:



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");
}
}


Than I should to configure PropertySourcesPlaceholderConfigurer to initialize properties from file:



@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;
}
}


What is correct form: ${catalina.home} or ${catalina/home} or how to specify relative path to my property file?


In configuration class I initialize Conditional beans and specify, that this config class depends on 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();
}
//....
}


But anyway I receive NPE in ProductionCondition:



return prodProfiler.equals("production");


Appreciate any help!


Aucun commentaire:

Enregistrer un commentaire