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.
Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.
@Bean is also an annotation that Spring uses to gather beans at runtime, but it's not used at the class level. Instead, we annotate methods with @Bean so that Spring can store the method's result as a Spring bean.
In Spring beans are basically components which are managed by Spring IoC Container. They are objects which create a backbone of Spring application. To create bean Spring container needs Java POJO and some kind of meta-data.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation.
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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With