Spring Boot 在控制器中的请求Map中启用conditionalOnProperty

34gzjxbg  于 2023-03-02  发布在  Spring
关注(0)|答案(3)|浏览(205)

我有一段代码-

@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文件中
我错过了什么吗?可能是类级别的注解?

svujldwt

svujldwt1#

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

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

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

wztqucjr

wztqucjr2#

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

x4shl7ld3#

@ConditionalOnProperty可用作@Bean方法上的方法级别注解only,如(在配置类中):

@Bean
  @ConditionalOnProperty(name = "myapp.feature.enabled", havingValue = "true")
  public MyFeature myFeature() {
      // create and return MyFeature instance
  }

我个人使用的@Value注解加载一个属性,然后根据属性值使用一个条件结构(if)。
例如:

@RestController
@RequestMapping("/my-endpoint")
public class MyController {

  @Value("${myapp.my-config-value}")
  private String myConfigValue;

  @GetMapping
  public String myMethod() {
    if ("disable".equals(myConfigValue)) {
      throw new IllegalStateException("This service is disabled.");
    }
    // if not disabled, do your stuff
    return myService.doStuff();
  }

}

相关问题