Searching...
Wednesday, 2 October 2013

Spring util:properties Example

04:19

Spring util:properties reads properties from a file location and we can inject this as java.util.Properties in to Bean. Here is one simple example to read properties from a class  path location and printing the property values

1. Create a Maven Project

Create a Maven Project with spring dependencies and add properties file in to main resources,here is the final structure

image

2. Create a Bean

Create a simple bean which required properties from class path.

package com.pretech;
import java.util.Properties;
public class SpringUtilProperties {
	Properties properties;
	public void setProperties(Properties properties) {
		this.properties = properties;
	}
	public void printProperties() {
		System.out.println(properties.toString());
	}
}

3. Create Spring configuration file (SpringConfig.xml)


In this configuration we are using <util:properties> to read properties and injecting Properties to SpringUtilProperties class which we created.

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util" 
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-3.0.xsd">
    <util:properties id="myproperties" location="classpath:/myproperties.properties" />
    <bean id="springUtilProperties" class="com.pretech.SpringUtilProperties">
        <property name="properties" ref="myproperties" />
    </bean>
</beans>

4. Create a Main class

package com.pretech;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SpringUtilMain {
 public static void main(String[] args) {
  Resource resource = new ClassPathResource("SpringConfig.xml");
  BeanFactory factory = new XmlBeanFactory(resource);
  SpringUtilProperties springutil = (SpringUtilProperties) factory
    .getBean("springUtilProperties");
  springutil.printProperties();
 }
}
}

5. Output



INFO: Loading properties file from class path resource [myproperties.properties]
{name=pretechsol, job=blogger}


0 comments: