SpringBoot日志收集之条件装配

  • Post author:
  • Post category:其他




什么是条件装配

众所周知,SpringBoot一大优势就是实现了bean的自动装配,但在某些特定场景中我们需要实现条件化自动装配,即根据配置文件决定bean是否被加载和配置



使用场景

例如:根据项目所需控制是否装配日志收集类、数据库连接池配置不完全则不进行数据源的装配等



如何使用


@ConfigurationProperties

+

@EnableConfigurationProperties

+

@ConditionalOnExpression


@ConfigurationProperties

:将配置文件转化为bean,方便读取配置文件信息

@ConfigurationProperties(prefix = "operation-logging")
@Data
public class OperationLoggingProperties {

    /**
     * 是否异步记录日志
     */
    private boolean async = false;

    /**
     * 是否启用日志
     */
    private boolean enabled = true;

}


@EnableConfigurationProperties

:将上述bean注入spring容器,使得@ConfigurationProperties生效,也可采用@Component+@ComponentScan


@ConditionalOnExpression

:条件表达式,返回true时才进行bean的实例化

@Configuration
@ComponentScan
@EnableConfigurationProperties(OperationLoggingProperties.class)
@ConditionalOnExpression("${operation-logging.enable:true}")
public class OperationLoggingAutoConfiguration {

    @Autowired
    private OperationLoggingProperties operationLoggingProperties;

    @Bean
    public OperationLoggingAspect operationLoggingAspect() {
        return new OperationLoggingAspect();
    }

    @Bean
    @ConditionalOnMissingBean
    public OperationLoggingExecutor operationLoggingExecutor() {
        System.out.println(operationLoggingProperties);
        OperationLoggingExecutor operationLoggingExecutor;
        if (operationLoggingProperties.isAsync()) {
            System.out.println("-----------加载默认异步实现类----------");
            operationLoggingExecutor = new DefaultAsyncOperationLoggingExecutor();
        } else {
            System.out.println("-----------加载默认同步实现类----------");
            operationLoggingExecutor = new DefaultOperationLoggingExecutor();
        }
        return operationLoggingExecutor;
    }

}



配置文件

operation-logging.enabled=true
operation-logging.async=true



版权声明:本文为qq_35928318原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。