Reputation: 907
The things I did are:
Propertyfile:url=sampleurl
Spring.xml:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath*:data.properties*"/>
</bean>
<bean id="dataSource" class="org.tempuri.DataBeanClass">
<property name="url" value="${url}"></property>
</bean>
beanclass
public class DataBeanClass extends PropertyPlaceholderConfigurer{
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
entry in web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:Spring*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Now my problem is I dont know what method of PropertyPlaceholderConfigurer should I override and what should I do to set the value of variable url such that I can call it from other classes using getproperty() method.
Upvotes: 5
Views: 76018
Reputation: 863
Please do the following process to get property file value in class.
Define the bean for property file in your spring.xml
<util:properties id="dataProperties" location="classpath:/data.properties"/>
keep your data.properties under src/main/resources.
Use the following code to get value from property file for e.g to get value of url key in data.properties
private @Value("#{dataProperties['url']})
String url;
Upvotes: 3
Reputation: 1688
Properties files can be made accessible to Spring via the following namespace element in Spring.xml
<context:property-placeholder location="classpath:data.properties" />
And then you can use like
@Autowired
private Environment env;
...
String url=env.getProperty("url"));
Note:
using <property-placeholder>
will not expose the properties to the Spring Environment – this means that retrieving the value like this will not work – it will return null
Upvotes: 0
Reputation: 10997
You can annotate your bean property like this, then spring will auto inject the property from your property file.
@Value("${url}")
private String url;
You dont have to extend PropertyPlaceholderConfigurer
Defining your bean like this will auto populate url as well, but annotation seems to be easiest way
<bean id="dataSource" class="org.tempuri.DataBeanClass">
<property name="url" value="${url}"></property>
</bean>
Upvotes: 12