Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC web application - enabling / disabling controller from property

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.

like image 792
Mircea Cazacu Avatar asked Jun 13 '13 05:06

Mircea Cazacu


2 Answers

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.

like image 94
nav3916872 Avatar answered Oct 01 '22 20:10

nav3916872


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.

like image 27
Jukka Avatar answered Oct 01 '22 19:10

Jukka