在Controller中的RequestMapping中启用ConditionalOnProperty

时间:2018-05-07 09:06:15

标签: spring-mvc spring-boot

我有一段代码 -

    @PropertySource(value = "classpath:securityConfig.properties", ignoreResourceNotFound = true)
    @Controller
    public class IndexController {
        private static final String LOGIN_PAGE           = "login";
        private static final String HOME_PAGE            = "home";
        private static final String LOBBY_PAGE           = "lobby";
        private static final String FORGOT_USER_PAGE     = "forgotUserName";
        private static final String FORGOT_PASSWORD_PAGE = "forgotPassWord";

        @ConditionalOnProperty(name = "auth.mode", havingValue = "fixed")
        @PreAuthorize("isAnonymous()")
        @RequestMapping(method = RequestMethod.GET, value = { "/login" })
        public String getIndexPage() {
            return LOGIN_PAGE;
        }
}

但是,ConditionalOn注释不能按预期工作。如果auth.mode不是fixed,我不希望控制器执行。注意 - auth.mode位于securityConfig.properties文件

我错过了什么吗?可能是班级的注释吗?

2 个答案:

答案 0 :(得分:0)

您应该将@ConditionalOnProperty注释移动到类,而不是方法。

@PropertySource(value = "classpath:securityConfig.properties", ignoreResourceNotFound = true)
@Controller
@ConditionalOnProperty(name = "auth.mode", havingValue = "fixed")
public class IndexController {
    ...
}

这意味着除非满足条件,否则整个控制器将不会存在于应用程序上下文中。

答案 1 :(得分:0)

编辑@PreAuthorize注释以添加条件

@PropertySource(value = "classpath:securityConfig.properties", ignoreResourceNotFound = true)
@Controller
public class IndexController {
    private static final String LOGIN_PAGE           = "login";
    private static final String HOME_PAGE            = "home";
    private static final String LOBBY_PAGE           = "lobby";
    private static final String FORGOT_USER_PAGE     = "forgotUserName";
    private static final String FORGOT_PASSWORD_PAGE = "forgotPassWord";

    @Value("${auth.mode:fixed}")
    private String authenticationMode;

    public String getAuthenticationMode(){
         return this.authenticationMode;
    }

    @PreAuthorize("isAnonymous() AND this.getAuthenticationMode().equals(\"fixed\")")
    @RequestMapping(method = RequestMethod.GET, value = { "/login" })
    public String getIndexPage() {
        return LOGIN_PAGE;
    }