Spring 3 : Reading .properties file

1. You may want to create a new spring project first.You can try it here:http://www.mkyong.com/spring3/spring-3-hello-world-example/

2. Create a new .properties file in your src/main/resources dir:
my.properties
-------------------
key1             value1
key2             value2

3.Create a new bean in your spring-context file(e.g. SpringBeans.xml).Simply put this:
<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>

4. And then in your java code:
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
            Properties mcls=(Properties) context.getBean("myProperties");
            System.out.println(mcls.getProperty("key1"));
            System.out.println(mcls.getProperty("key2"));
Output:

value1
value2
5.In case of web app.You can try this code in your controller:

private static XmlBeanFactory beanFactory = new XmlBeanFactory(
new ClassPathResource("SpringBeans.xml"));
Properties mcls=(Properties) context.getBean("myProperties");

No comments:

Post a Comment