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
<?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-
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.javapublic 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());
}
}
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 fileimport 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();
}
}
Test.name=navin
Test.age=21
Spring.xmlTest.age=21
<?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
Age=21
For Further Reading,
0 comments:
Post a Comment