文章目录
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.测试
到此该博客的任务已经完成,是不是配置起来很简单呢,感兴趣的小伙伴可以自己试试。
4.项目配套代码
创作不易,要是觉得我写的对你有点帮助的话,麻烦在github上帮我点下 Star
【SpringBoot框架篇】其它文章如下,后续会继续更新。
- 1.搭建第一个springboot项目
- 2.Thymeleaf模板引擎实战
- 3.优化代码,让代码更简洁高效
- 4.集成jta-atomikos实现分布式事务
- 5.分布式锁的实现方式
- 6.docker部署,并挂载配置文件到宿主机上面
- 7.项目发布到生产环境
- 8.搭建自己的spring-boot-starter
- 9.dubbo入门实战
- 10.API接口限流实战
- 11.Spring Data Jpa实战
- 12.使用druid的monitor工具查看sql执行性能
- 13.使用springboot admin对springboot应用进行监控
- 14.mybatis-plus实战
- 15.使用shiro对web应用进行权限认证
- 16.security整合jwt实现对前后端分离的项目进行权限认证
- 17.使用swagger2生成RESTful风格的接口文档
- 18.使用Netty加websocket实现在线聊天功能
- 19.使用spring-session加redis来实现session共享
- 20.自定义@Configuration配置类启用开关
- 21.对springboot框架编译后的jar文件瘦身
- 22.集成RocketMQ实现消息发布和订阅
- 23.集成smart-doc插件零侵入自动生成RESTful格式API文档
- 24.集成FastDFS实现文件的分布式存储
本文标题:【SpringBoot框架篇】20.自定义@Configuration配置类启用开关
本文链接:https://blog.quwenai.cn/post/2301.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。








还没有评论,来说两句吧...