如何在spring xml配置中注入环境变量?
在我们设置环境变量之后,AWS在http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.managing.html中讨论了System.getProperty("JDBC_CONNECTION_STRING")
。 除了我不能在我的Spring XML配置代码中调用System.getProperty
,我也无法调用资源包快捷方式,因为资源包本身必须以某种方式提取这些环境变量来为它们服务。 请帮助我转换此示例配置以使用环境变量? 🙂
300000 60000
我无法理解人们在这里做了什么:
我可以为Spring FileSystemResource使用基于环境变量的位置吗? 哪个适用于最近的春季版?
首先在配置中添加
元素。
然后只需在配置中使用占位符。
确保占位符名称与您设置的变量匹配。
如果使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类加载属性文件,则可以将属性systemPropertiesMode
设置为值SYSTEM_PROPERTIES_MODE_OVERRIDE
。
在spring.xml中你将拥有这个bean:
classpath://file.properties
Spring将以这种方式加载系统属性:
在尝试指定的属性之前,首先检查系统属性。 这允许系统属性覆盖任何其他属性源。
通过这种方式,您应该能够将系统属性作为普通属性读取。
对于使用JavaConfig的人:
在@Configuration文件中,我们需要:
@Bean public static PropertyPlaceholderConfigurer properties() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ClassPathResource[] resources = new ClassPathResource[ ] { new ClassPathResource("db.properties") }; ppc.setLocations( resources ); ppc.setIgnoreUnresolvablePlaceholders( true ); ppc.setSearchSystemEnvironment(true); return ppc; } @Value("${db.url}") private String dbUrl; @Value("${db.driver}") private String dbDriver; @Value("${db.username}") private String dbUsername; @Value("${db.password}") private String dbPassword; @Bean public DataSource db() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(dbUrl); dataSource.setDriverClassName(dbDriver); dataSource.setUsername(dbUsername); dataSource.setPassword(dbPassword); return dataSource; }
重要的是行:ppc.setSearchSystemEnvironment(true);
之后在db.properties中,我有:
db.url = ${PG_URL} db.driver = ${PG_DRIVER} db.username = ${PG_USERNAME} db.password = ${PG_PASSWORD}