Close

Spring MVC - Path Patterns with Placeholders

[Last Updated: Jan 26, 2017]

Spring MVC 

Patterns in @RequestMapping annotations support ${...} placeholders which can be substituted with local properties and/or system properties and environment variables. Following example shows how to achieve that.


Example

The Controller

@Controller
public class MyController {

  @RequestMapping("/${app.path}")
  @ResponseBody
  public String handleTestRequest () {

      return "test output";
  }
}

src/main/resources/my-props.properties

app.path = test/test2

JavaConfig class

@EnableWebMvc
@ComponentScan("com.logicbig.example")
@PropertySource("classpath:my-props.properties")
public class AppConfig {

}

WebApplicationInitializer implementation

public class WebAppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses () {
      return new Class<?>[]{AppConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses () {
      return null;
  }

  @Override
  protected String[] getServletMappings () {
      return new String[]{"/"};
  }
}

Run embedded tomcat

mvn tomcat7:run-war

Output



Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.5.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

path-pattern-placeholder Select All Download
  • path-pattern-placeholder
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java
          • resources

    See Also