从PropertySource访问Spring属性

时间:2014-01-07 21:12:04

标签: java spring

我想在属性文件中读取我的数据源连接信息,并能够从我的Spring-Datasource.xml文件中获取这些值。这就是我所拥有的:

代码

Properties prop = properties.load(new FileReader(fileName));
PropertySource myPropertySource = new MyPropertySource(prop);

AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"/applicationContext.xml"},false);
applicationContext.getEnvironment().getPropertySources().addFirst(myPropertySource);
System.out.println(applicationContext.getEnvironment().getProperty("database.username"));
applicationContext.refresh();

这将显示database.username的正确值。

弹簧Datasource.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}"/>
    <property name="url" value="${database.url}"/>
    <property name="username" value="${database.username}"/>
    <property name="password" value="${database.password}"/>
</bean>

我最终得到以下错误,它似乎找不到任何属性。

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [Spring-Datasource-dev.xml]: Could not resolve placeholder 'database.driver' 

我错误地访问了它们,还是遗漏了什么?感谢。

1 个答案:

答案 0 :(得分:3)

你有错别字......而不是: -

<property name="username" value="%{database.username}"/>
<property name="password" value="%{database.password}"/>

......这样做: -

<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>

如果这不能解决问题,那么您可能忘记定义PropertyPlaceholderConfigurer: -

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:messages.properties"/>
</bean>

如果您尝试加载动态属性文件,可以尝试以下操作:PropertyPlaceholderConfigurer: can i have a dynamic location value