How to set properties of a bean from properties file.......
This can be accomplished by PropertyPlaceholderConfigurer class
Bean.java
package props;
public class Bean {
private String value1, value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}
This can be accomplished by PropertyPlaceholderConfigurer class
Bean.java
package props;
public class Bean {
private String value1, value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}
ApplicationResource.properties
bean.value1=Sidhartha
bean.value2=Ray
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean name="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="ApplicationResource.properties"/>
</bean>
<bean id="bean" class="props.Bean">
<property name="value1" value="${bean.value1}"/>
<property name="value2" value="${bean.value2}"/>
</bean>
</beans>
Client.java
package props;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
Bean bean = context.getBean("bean", Bean.class);
System.out.println(bean.getValue1() + " - " + bean.getValue2());
}
}
No comments:
Post a Comment