开发者

Managing deployment-specific configurations with Spring

开发者 https://www.devze.com 2023-03-09 22:53 出处:网络
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 f

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号