We can read and inject the property from property file in spring. The below code will show you how you can read the property from property file and inject that properties to the List Object by using spring-config.xml file.
Customer.java
package com.evon;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
public class Customer {
@Value("${user.email}")
private String email;
private List<Object> list;
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public void print()
{
System.out.println(email);
}
}
spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:h="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:property-placeholder location="classpath*:properties/*.properties"/>
<context:annotation-config />
<bean id="person" class="com.evon.Person">
<property name="name" value="Manish" />
<property name="address" value="New Delhi" />
<property name="age" value="25" />
</bean>
<bean id="customer" class="com.evon.Customer">
<!-- java.util.List -->
<property name="list">
<list>
<value>${user.name}</value>
<value>${user.email}</value>
<value>${user.age}</value>
</list>
</property>
</bean>
</beans>
App.java
package com.evon;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Customer cust = (Customer) context.getBean("customer");
System.out.println(cust.getList());
cust.print();
}
}
Properties.properties
user.email=manish@evontech.com
user.name=manish
user.age=25
In above code we have define some property in Properties.properties file. We Inject all the values of property file in List object by using spring-config.xml file. We can also directly read the value of user.email from property file in Customer.java.
0 Comment(s)