Friday, June 1, 2012

Spring Framework- Configure property file with xml(PropertyPlaceholderConfigurer)


In Xml no need to directly put the values of the properties, we can also use Properties file to place the value of properties.It is define in given example-
Directory Structure-



Class Test.java
package com.test;
public class Test {

private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show()
{
System.out.println("Name="+getName());
System.out.println("Age="+getAge());
}
}
Class Main.java
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test t=(Test) context.getBean("test");
t.show();
}
}
a.Properties file
Test.name=navin
Test.age=21

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="a.properties"></property>
</bean>
<bean id="test" class="com.test.Test">
<property name="name" value="${Test.name}"></property>
<property name="age" value="${Test.age}"></property>
</bean>
</beans>

Output is-
Name=navin
Age=21


For Further Reading,
General, Java, spring

0 comments:

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.