前言
之前看过SSM(十四) 基于annotation的http防重插件的朋友应该记得我后文说过之后要用SpringBoot来进行重构。
这次采用自定义的
starter的方式来进行重构。
关于starter(起步依赖)其实在第一次使用SpringBoot的时候就已经用到了,比如其中的:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
我们只需要引入这一个依赖SpringBoot就会把相关的依赖都加入进来,自己也不需要再去担心各个版本之间的兼容问题(具体使用哪个版本由使用的spring-boot-starter-parent版本决定),这些SpringBoot都已经帮我们做好了。
01.jpg
Spring自动化配置
先加入需要的一些依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--aop相关--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--redis相关--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <!--配置相关--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!--通用依赖--> <dependency> <groupId>com.crossoverJie</groupId> <artifactId>sbc-common</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency>
创建了CheckReqConf配置类用于在应用启动的时候自动配置。
当然前提还得在resources目录下创建META-INF/spring.factories配置文件用于指向当前类,才能在应用启动时进行自动配置。
spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration= \com.crossoverJie.request.check.conf.CheckReqConf
使用条件化配置
试着考虑下如下情况:
因为该插件是使用
redis来存储请求信息的,外部就依赖了redis。如果使用了该插件的应用没有配置或者忘了配置redis的一些相关连接,那么在应用使用过程中肯定会出现写入redis异常。
如果异常没有控制好的话还有可能影响项目的正常运行。
那么怎么解决这个情况呢,可以使用Spring4.0新增的条件化配置来解决。
解决思路是:可以简单的通过判断应用中是否配置有spring.redis.hostredis连接,如果没有我们的这个配置就会被忽略掉。
实现代码:
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.crossoverJie.request.check.interceptor,com.crossoverJie.request.check.properties") //是否有redis配置的校验,如果没有配置则不会加载改配置,也就是当前插件并不会生效 @Conditional(CheckReqCondition.class) public class CheckReqConf { }
具体校验的代码CheckReqCondition:
public class CheckReqCondition implements Condition { private static Logger logger = LoggerFactory.getLogger(CheckReqCondition.class); @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) { //如果没有加入redis配置的就返回false String property = context.getEnvironment().getProperty("spring.redis.host"); if (StringUtils.isEmpty(property)){ logger.warn("Need to configure redis!"); return false ; }else { return true; } } }
