Managing deployment-specific configurations with Spring
What strategies have people developed for controlling deployment configurations with Spring? I've already extracted out the environmental details (e.g. jdbc connection parameters) into a properties file, but I'm loo开发者_StackOverflow中文版king for some way of managing deployment details that aren't simple strings. Specifically, I'm currently using a locally configured datasource while doing development, and JNDI on our application servers (DEV, QA).
I've got an applicationContext.xml with the following two lines,
<import resource="spring/datasource-local-oracle.xml"/>
<import resource="spring/datasource-jndi.xml"/>
and I comment out whichever datasource isn't being used in that instance. There's got to be a better way to do this though. Thoughts, ideas, suggestions?
Use @Bean to define your datasource in code, rather than in XML. That way you can apply conditional logic to how the bean is created. For example:
@Value("${url:jdbc:hsqldb:mem:memdb}")
String url;
// username, password, etc
@Value("${jndiName:}")
String jndiName;
@Bean
public DataSource dataSource() {
DataSource ds;
if (jndiName == "") {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName(driverClassName);
bds.setUrl(url);
bds.setUsername(username);
bds.setPassword(password);
ds = bds;
} else {
JndiObjectFactoryBean = jndiFactory = new JndiObjectFactoryBean();
jndiFactory.setJndiName("java:/" + jndiName);
jndiFactory.afterPropertiesSet();
ds = (DataSource) jndiFactory.getObject();
}
return ds;
}
精彩评论