- SpringBoot项目中,有时候需要利用配置来开启或关闭某些功能的配置项,来达到利用配置参数控制功能的目的,@ConditionalOnProperty注解就是为此设计的。它可以用于类和方法之上。
- 实例代码如下:
@Configuration
public class WebConfig {
@Bean
@ConditionalOnProperty(prefix = "rest", name = "auth-open", havingValue = "true", matchIfMissing = true)
public AuthFilter jwtAuthenticationTokenFilter() {
return new AuthFilter();
}
}
- 注解参数解释:
- prefix = "rest":application.properties配置文件中,有关本配置项的前缀。
- name = "auth-open":application.properties配置文件中,本次配置项的key
- havingValue = "true":从配置文件读取的值跟havingValue中设置的值做比较;如果一样则返回true,否则返回false。如果返回值为false,则该configuration不生效;为true才生效。
- matchIfMissing = true:表示如果没有在application.properties匹配到该属性参数时,默认返回true,即不配置时也满足条件。
- 上面代码的意思是:
- 是否启动jwt的的配置,如果application.properties文件中没有设置该参数就启用jwt;
- 如果设置了true就启动,如果false就关闭;
- application.properties文件配置如下:
#jwt鉴权机制是否开启(true或者false)
rest.auth-open = true