java – 在spring中使用.properties而不使用xml配置
发布时间:2020-12-15 04:07:29 所属栏目:Java 来源:网络整理
导读:我在春季使用基于 Java的Configuration和x000的文章中找到了一种使用.properties文件的方法.插图如下.我的问题是“有没有办法在不使用xml文件的情况下仅使用基于Java的配置来使用.properties文件?” 有没有办法在下面的代码中省略@ImportResource并使用基于
我在春季使用基于
Java的Configuration和x000的文章中找到了一种使用.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); // ... } 解决方法
试试这样
@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/了解更多信息 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |