条件注解之@ConditionalOnProperty注解:通过配置文件的配置来控制配置类是否加入spring的IOC容器

发布时间 2023-07-04 18:04:25作者: 周文豪

一、条件注解分类

常见的@ConditionalOnxxx开头的注解我们称之为条件注解,常见的条件注解有

  • class条件注解:@ConditionalOnClass
  • bean条件注解:@ConditionalOnBean
  • 属性条件注解:@ConditionalOnProperty

@ConditionalOnProperty:如果有指定的配置,条件生效

@ConditionalOnBean:如果有指定的Bean,条件生效;

@ConditionalOnMissingBean:如果没有指定的Bean,条件生效;

@ConditionalOnMissingClass:如果没有指定的Class,条件生效;

@ConditionalOnWebApplication:在Web环境中条件生效;

@ConditionalOnExpression:根据表达式判断条件是否生效。

 这几个注解通常会结合使用,一般都是在配置类中使用,SpringBoot各种xxxxAutoCconfiguration都用到了这些注解,这也是SpringBoot自动装配的重要工具。

二、@ConditionalOnProperty注解

简单来讲,一般是在配置类上或者是@Bean修饰的方法上,添加此注解表示一个类是否要被Spring上下文加载,若满足条件则加载,若不满足条件则不加载

我们在application.properties中配置的各种配置,添加配置之后即生效,就是这么控制的。

prefix:配置文件中的前缀。

name:配置的名字。

havingValue:它的值与配置文件的值对比,当两个值相同,类会被加载到spring的IOC容器中。

matchIfMissing:缺少该配置时是否可以加载,如果为true,没有该配置属性时也会正常加载,反之则不会生效。

@ConditionalOnProperty源码

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnPropertyCondition.class})
public @interface ConditionalOnProperty {
    String[] value() default {};

    String prefix() default "";

    String[] name() default {};

    String havingValue() default "";
boolean matchIfMissing()
default false; }

首先看matchIfMissing属性,用来指定如果配置文件中未进行对应属性配置时的默认处理:默认情况下matchIfMissing为false,也就是说如果未进行属性配置,则自动配置不生效如果matchIfMissing为true,则表示如果没有对应的属性配置,则自动配置默认生效

如:http编码的自动配置类中,当配置文件中没有配置spring.http.encoding.enabled,自动配置仍然会生效。

@Configuration
@EnableConfigurationProperties({HttpProperties.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {...}

三、使用@ConditionalOnProperty注解

@ConditionalOnProperty注解是控制被注解的类中其他注解(@Component和@Configuration两个注解)是否生效

1、在配置类中控制@Configuration是否生效

在spring boot中有时候需要控制配置类中的Bean是否生效,可以使用@ConditionalOnProperty注解来控制@Configuration是否生效.

@Configuration被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

@Configuration
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
public class FilterConfig {
    @Bean
    public FilterRegistrationBean getFilterRegistration() {
        FilterRegistrationBean filterRegistration  = new FilterRegistrationBean(new LoginFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }
}

 配置文件中代码

filter.loginFilter=true

通过@ConditionalOnProperty控制配置类是否生效,可以将配置与代码进行分离,实现了更好的控制配置。

@ConditionalOnProperty实现是通过havingValue与配置文件中的值对比,相同则配置类生效,反之失效

2、在切面类中控制@Component是否生效

@Slf4j
@Aspect
@Component
@ConditionalOnProperty(prefix = "system.log", name = "enabled", havingValue = "true")
public class LogAspect {

    //成功的标志
    private final static boolean SUCCESS = true;

    @Resource
    private HttpServletRequest request;

    @Autowired
    private JWTService jwtService;
    @Autowired
    private SystemLogService systemLogService;

    /**
     * 配置切点,拦截Controller中添加@Log注解的方法
     */
    @Pointcut("@annotation(com.ljxx.common.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before("logPointCut()")
    public void doBeforeAdvice(JoinPoint joinPoint) {

    }

    /**
     * 后置通知
     *
     * @param obj
     * @throws IOException
     */
    @AfterReturning(returning = "obj", pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint, Object obj) throws Exception {
        handleLog(joinPoint, obj, null);
    }

    /**
     * 异常通知
     *
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) throws Exception {
        handleLog(joinPoint, null, e);
    }

    /**
     * 日志处理
     *
     * @param result
     * @param e
     */
    private void handleLog(JoinPoint joinPoint, Object result, Exception e) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ...
        systemLogService.addLog(systemLog);
    }

    /**
     * 截取字符串
     *
     * @param val
     * @return
     */
    private String getText(String val) {
        return StrUtil.sub(val, 0, 4000);
    }


}

配置中的代码

#开启日志存储
system.log.enabled=true

 @ConditionalOnProperty是通过havingValue与配置文件中的值对比,如果返回为true则@Component注解生效,反之失效。

3、在配置类中控制@Component是否生效

(1)、配置文件配置

zs.name=张三
zs.age=14
config.isActive=1

(2)、配置类

@Component
@ConfigurationProperties(prefix = "zs")
@ConditionalOnProperty(prefix = "config",name = "isActive",havingValue = "1")
@Data
public class ConfigurationBean {
    private String name;
    private Integer age;
}

@ConditionOnPropertiy注解的意思是:如果配置文件中config.isActive=1,则该@Component注解生效。

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射

(3)、测试配置类的@Component注解是否生效

@RestController
public class HelloController {
    @Autowired
    private ConfigurationBean config;

    @GetMapping("/config")
    private String testConfigurationProperties(){
        System.out.println(config);
        return "SUCCESS!!!";
    }
}

启动项目,浏览器访问:http://localhost:8080/config,控制台打印如下:

ConfigurationBean(name=张三, age=14)

修改配置文件如下:

config.isActive=2

启动项目,发现启动失败,如下所示:

即spring的IOC容器中没有找到ConfigurationBean对象。