[英]Use .properties without using xml configuration in spring
I found a way to use .properties files in spring when using Java-based Configuration and xml from this article. 我找到了一种方法使用基于Java的配置和XML时使用.properties文件在春天这个文章。 The illustrations is as follows.
插图如下。 My question is " Is there any way to use .properties files only using Java-based configuration without using xml files? "
我的问题是“ 有没有办法在不使用xml文件的情况下仅使用基于Java的配置来使用.properties文件? ”
ie Is there any way to omit @ImportResource
in following code and use pure Java-based configuration? 即在以下代码中是否有任何方法可以省略
@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);
}
}
properties-config.xml 性能-config.xml中
<beans>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>
jdbc.properties jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=
Sample Main method 样本主要方法
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
TransferService transferService = ctx.getBean(TransferService.class);
// ...
}
try like this 试试这样
@Configuration
@PropertySource("/app.properties")
public class Test {
@Value("${prop1}")
String prop1;
@Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
or using Environment 或使用环境
@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"));
}
}
read this article http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/ for more info 阅读这篇文章http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/了解更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.