Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable ConditionalOnProperty in a RequestMapping in Controller

I have a piece of code -

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

However, the ConditionalOn annotation doesnt work as expected. I do not want the controller to execute if auth.mode is anything other than fixed. Note - auth.mode is in securityConfig.properties file

Am I missing something? Probably an annotation at class level?

like image 863
Prateek Narendra Avatar asked Oct 11 '25 18:10

Prateek Narendra


1 Answers

You should move the @ConditionalOnProperty annotation to the class, not on the method.

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

This will mean the entire controller will not exist in the application context unless the condition is satisfied.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!