25

Is it possible to define the value of a @RequestMapping annotation in Spring by defining it in a properties file?

Actually, I do something like:

@Controller
@RequestMapping("/xxx")
public class MyController {
...
}

But I would like to store the path /xxx in a properties file. Why? For instance, it is less likely that I do mystakes in my templates if I rename the path in the controller.

In other framework this is allowed (see Symfony, for instance).

JeanValjean
  • 17,172
  • 23
  • 113
  • 157

3 Answers3

48

It should be possible to use placeholders in @RequestMapping, like for example @RequestMapping("${foo.bar}"). Take a look at the documentation for more details:

Patterns in @RequestMapping annotations support ${…​} placeholders against local properties and/or system properties and environment variables. This may be useful in cases where the path a controller is mapped to may need to be customized through configuration. For more information on placeholders, see the javadocs of the PropertyPlaceholderConfigurer class.

Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
  • I was wondering about something like that (as done in `@Value`), but when I tried to call in `@RequestMapping` a key defined in the `application.properties` file, e.g. my.xx=/xxx, the IntelliJ Idea IDE reported the following problem: `Cannot resolve @PathVariable my.xx`. Any idea? – JeanValjean Aug 09 '15 at 13:40
  • @JeanValjean And does it work when you run the app? IntelliJ inspections are not always perfect, so this might just be a false-positive – Bohuslav Burghardt Aug 09 '15 at 13:41
  • My mistake, if I add the definition in the application.properties file, everything is ok. The problem is when I try to load the string from another properties file. I have to find a way to read from it. – JeanValjean Aug 09 '15 at 14:04
  • @JeanValjean Hello, have you found any ways to read from another properties file? – Leo.W Jul 24 '18 at 00:11
3

Thx for the help. It is my contribution... No dependencies are necessary because maven do everything by itself.

In the property file - use maven interpolation, such as below:

vs= v1

us= users
me= messages

url.user=${vs}/${us}
url.mess=${vs}/${me}

In your destiny file, for example controller/resource (in mycase):

@RestController
//@RequestMapping("v1/users") <<<<<<instead this
@RequestMapping("${url.user}")<<<<<<use this
@Api(value = "API RESTFUL)
public class UserResource {
//
GtdDev
  • 748
  • 6
  • 14
1

As bohuslav burghardt has mentioned this is totally possible.

So if you have a common domain stored in your application.properties file you can use placeholders to call it in your controller/s and even chain placeholders & text together.

For Example...
In your .properties file

app.domain = mydomain/v1

In the controller

@RestController
@RequestMapping("${app.domain}/my-controller")
public class MyController {
AussieDev81
  • 454
  • 5
  • 11