【SpringBoot框架篇】20.自定义@Configuration配置类启用开关

1.简介

在这里插入图片描述
通过@Configuration注解标识的类默认都会被spring加载,但是我们有时候想要通过开关来决定要不要加载,这个时候就需要该博客讲解的内容。
我目前了解的两种实现方式如下

  • 1.自定义@Enable注解
  • 2.通过配置文件配置

2.自定义@Enable注解

我常用的例如:@EnableCaching(缓存)、@EnableScheduling(定时任务),@EnableJpaAuditing(审计),这类注解就像开关一样,只要在SpringBoot启动类上加这类注解,就能开启相关的功能。

本文以日志打印的功能为基础,实现此功能

2.1.定义一个LogFilter

public class LogFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("记录请求日志");
        chain.doFilter(request, response);
        System.out.println("记录响应日志");
    }

    @Override
    public void destroy() { }
    
}

2.2.注册LogFilter

注意,这里用了@ConditionalOnWebApplication注解,没有直接使用@Configuration注解。

@ConditionalOnWebApplication
public class LogFilterWebConfig {

    @Bean
    public LogFilter buildFilter() {
        return new LogFilter();
    }
}

2.3.定义开关@EnableLog注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(LogFilterWebConfig.class)
public @interface EnableLog {
}

2.4.启动类上添加注解

@SpringBootApplication
@EnableLog
public class ConfigSwitchApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigSwitchApplication.class, args);
    }

}

2.5.测试

添加一个测试的接口

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        System.out.println("test接口被调用");
        return "test";
    }
}

启动项目,然后访问http://localhost:8020/test
在这里插入图片描述
可以看到控制台已经实现了打印log的功能,我们把@EnableLog注释掉再启动测试一下
在这里插入图片描述
在这里插入图片描述
可以看到日志信息并没有被打印,代表着LogFilterWebConfig这个类没有被spring加载。

3.通过配置文件配置

使用@ConditionalOnProperty注解指定配置项实现

3.1.修改LogFilterWebConfig类

  • 通过其两个属性name以及havingValue来实现的,其中name用来从application.yml中读取某个属性值。
  • 如果该值为空,则返回false;
  • 如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。
  • 如果返回值为false,则该configuration不生效;为true则生效。
@ConditionalOnProperty(name = "mylog.enable", havingValue = "true")
@Configuration
public class LogFilterWebConfig {
    @Bean
    public LogFilter buildFilter() {
        return new LogFilter();
    }
}

3.2.application.yml文件中添加配置

mylog:
  enable: true

3.3.测试

mylog.enable值为true时候调用接口如下
在这里插入图片描述

mylog.enable值为false时候调用接口如下
在这里插入图片描述

到此该博客的任务已经完成,是不是配置起来很简单呢,感兴趣的小伙伴可以自己试试。

4.项目配套代码

gitee代码地址

创作不易,要是觉得我写的对你有点帮助的话,麻烦在gitee上帮我点下 Star

【SpringBoot框架篇】其它文章如下,后续会继续更新。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皓亮君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值