在春天使用.properties而不使用xml配置

时间:2013-02-11 02:52:47

标签: java spring

在使用基于Java的Configuration和this文章中的xml时,我找到了一种在春天使用.properties文件的方法。插图如下。我的问题是“有没有办法在不使用xml文件的情况下仅使用基于Java的配置来使用.properties文件?

即有没有办法在下面的代码中省略@ImportResource并使用基于Java的纯配置?

@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {
   private @Value("${jdbc.url}") String url;
   private @Value("${jdbc.username}") String username;
   private @Value("${jdbc.password}") String password;

   public @Bean DataSource dataSource() {
      return new DriverManagerDataSource(url, username, password);
   }
}

属性-config.xml中

<beans>
   <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>

jdbc.properties

jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=

主要方法示例

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
   TransferService transferService = ctx.getBean(TransferService.class);
   // ...
}

1 个答案:

答案 0 :(得分:7)

试试这个

@Configuration
@PropertySource("/app.properties")
public class Test {
    @Value("${prop1}")
    String prop1;

    @Bean
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

或使用环境

@Configuration
@PropertySource("/app.properties")
public class Test {
    @Autowired
    Environment env;

    @Bean
    public DataSource dataSource() {
        return new DriverManagerDataSource(env.getProperty("url"), env.getProperty("username"), env.getProperty("password"));
    }
}

阅读这篇文章http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/了解更多信息