Mircea Cazacu
Mircea Cazacu

Reputation: 103

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.

Upvotes: 9

Views: 7848

Answers (2)

nav3916872
nav3916872

Reputation: 998

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.

Upvotes: 5

Jukka
Jukka

Reputation: 4663

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.

Upvotes: 16

Related Questions