Spring MVC Web应用程序 - 从属性启用/禁用控制器

Mir*_*acu 7 model-view-controller spring tomcat web

我有一个在Tomcat中运行的Web应用程序,并使用Spring MVC来定义控制器和映射.我有以下课程:

@Controller("api.test")
public class TestController {

        @RequestMapping(value = "/test", method = RequestMethod.GET)   
        public @ResponseBody String test(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
            // body
        }
}
Run Code Online (Sandbox Code Playgroud)

我想根据某处定义的属性(例如文件)使这个控制器和".../test"路径可用.如果属性是假设,我希望应用程序的行为就像该路径不存在一样,如果它是真的,则表现正常.我怎样才能做到这一点?谢谢.

Juk*_*kka 13

如果您使用的是Spring 3.1+,请仅在测试配置文件中使控制器可用:

@Profile("test")
class TestController {
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后通过在Tomcat启动时传递以下系统属性来启用该配置文件:

-Dspring.profiles.active=test
Run Code Online (Sandbox Code Playgroud)

要禁用控制器,只需省略给定的配置文件.


nav*_*872 5

另一种方法(可能是更简单的方法)是在 RestController/Controller 中使用@ConditionalOnProperty注释。

    @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
        }
}
Run Code Online (Sandbox Code Playgroud)

这里 yml 属性中的 testcontroller.enabled 属性表示,如果未设置为 true ,则永远不会创建 TestController Bean。

提示:我建议您使用 RestController 而不是 Controller,因为它默认添加了 @ResponseBody。您可以使用 @ConditionalOnExpression 获得相同的解决方案,但由于 SpEL 评估而速度稍慢。