在控制器RequestMapping启用ConditionalOnProperty(Enable C

2019-11-04 17:48发布

我有一段代码 -

    @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.modesecurityConfig.properties文件

我缺少的东西吗? 可能是在类级别的注释?

Answer 1:

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

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

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



Answer 2:

编辑@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;
    }


文章来源: Enable ConditionalOnProperty in a RequestMapping in Controller