I have a web application running in 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 ".../test" path available according to a property defined somewhere (e.g. file). If the property is, lets say, false, I would like the app to behave as if that path doesn't exist and if it is true, to behave normally. How can I do this? Thanks.
Another way of doing it , may be simpler way of doing it, is to use @ConditionalOnProperty annotation with your 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 testcontroller.enabled property in your yml properties say ,if not set to true , the TestController Bean is never created.
Tip: I suggest you to use RestController instead of Controller as its has @ResponseBody added by default. You can use @ConditionalOnExpression to arrive at the same solution but is little slower due to SpEL evaluation.
If you are using Spring 3.1+, make the controller available only in the test profile:
@Profile("test")
class TestController {
...
}
then enable that profile by e.g. passing the following system property at Tomcat boot:
-Dspring.profiles.active=test
To disable the controller simply omit the given profile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With