Hi everyone in this post I just wanna share a simple sticky code in Spring MVC which used to mapping your @RequestMapping annotation to a properties file. It’s called Property Source, and it would be an advantage to make your URL Request Mapping more managable. Because you put your URL Request Mapping in a single file. Let’s look at the code
1. Add annotation @PropertySource in your web configuration class
@Configuration
@EnableWebMvc
@PropertySource("classpath:/config/mapping-controllers.properties")
@ComponentScan(basePackages = "com.estartup")
@EnableTransactionManagement
public class WebApplicationConfiguration extends WebMvcConfigurerAdapter
implements ApplicationContextAware {
private ApplicationContext applicationContext;
private org.apache.commons.configuration.Configuration _config = ConfigManager.getConfiguration();
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public static PropertyResourceConfigurer propertyResourceConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2. Create a properties file in src/config package which named mapping-controllers.properties, add put an example (test)
test=/test
3. In your Controller class you can put ${test} inside the @RequestMapping annotation, ${test} is taken from mapping-controllers.properties which you made before
package com.estartup.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("${test}")
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String defaultHandler(){
System.out.println("entering test controller : default handler ");
return "company/company_list";
}
}
Good Luck !!