Sunday, July 16, 2017

Spring MVC: Inject Properties file into java.util.Map

You can inject .properties as a map in your class using @Resource annotation.

If you are working with XML based configuration, then add below bean in your spring configuration file:
  
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

Then you can pick them up in your application as a Map:
 
@Resource(name = "myProperties")
private Map<String, String> myProperties;


 Full Code:

1. Configuration for the Map.


package com.controller.utility;


import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class MessageUtil {

    @Bean(name = "messages")
    public static PropertiesFactoryBean mapper() {
            PropertiesFactoryBean bean = new PropertiesFactoryBean();
            bean.setLocation(new ClassPathResource(
                    "message.properties"));
            return bean;
    }
}


2. Use Map in Controller to access the value by using URL.


package com.controller.test;

import java.util.Map;

import javax.annotation.Resource;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @Resource(name="messages")
    private Map messages;
  
   
    @RequestMapping(value="/{messageId}")
    @ResponseBody
    public String getMessage(@PathVariable("messageId") String messageId)
    {
        return messages.get(messageId);
    }
}


3. Sample message.properties file under src/main/resources.

method0=This is method0
method1=This is method1
method2=This is method2
method3=This is method3
method4=This is method4
method5=This is method5
method6=This is method6
method7=This is method7
method8=This is method8
method9=This is method9