Haeflinger
Haeflinger

Reputation: 465

Access Spring properties from PropertySource

I want to read in a properties file with my data source connection information and be able to get those values from my Spring-Datasource.xml file. Here is what I have:

Code

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();

This will display the correct value for database.username.

Spring-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>

I end up with the following error, it does not seem to find any of the properties.

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' 

Am I accessing them wrong, or missing something? Thanks.

Upvotes: 2

Views: 1614

Answers (1)

limc
limc

Reputation: 40170

You have typos... instead of this:-

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

... do this:-

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

If that doesn't solve the problem, then you may have forgotten to define PropertyPlaceholderConfigurer:-

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

If you are trying to load dynamic properties file, you can try this: PropertyPlaceholderConfigurer: can i have a dynamic location value

Upvotes: 3

Related Questions