Spring MVC Web Application - turning on / off a controller from a property

I have a web application running on Tomcat and using Spring MVC to define controllers and mappings. I have the following class:

@Controller("api.test") public class TestController { @RequestMapping(value = "/test", method = RequestMethod.GET) public @ResponseBody String test(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { // body } } 

I would like to make this controller and the path "... / test" available according to the definition defined somewhere (like a file). If the property is, say, false, I would like the application to behave as if this path does not exist and if it is true, behave normally. How can i do this? Thanks.

+6
source share
2 answers

If you are using Spring 3.1+, make the controller available only in the test profile:

 @Profile("test") class TestController { ... } 

then enable this profile, for example. passing the following system property when booting Tomcat:

 -Dspring.profiles.active=test 

To disable the controller, simply omit the specified profile.

+12
source

Another way to do this might be an easier way to do this: use the @ConditionalOnProperty annotation using RestController / Controller.

  @RestController("api.test") @ConditionalOnProperty(name = "testcontroller.enabled", havingValue = "true") public class TestController { @RequestMapping(value = "/test", method = RequestMethod.GET) public String test(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { // body } } 

Here, the testcontroller.enabled property in your yml properties says that if it is not set to true, the TestController Bean is never created.

Tip . I suggest you use RestController instead of Controller, as @ResponseBody is added by default. You can use @ConditionalOnExpression to arrive at the same solution, but a bit slower due to the SpEL score.

+2
source

Source: https://habr.com/ru/post/947184/


All Articles