1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot-version}</version>
<optional>true</optional>
</dependency>
2.编写代码
2.1定义属性接收类
@ConfigurationProperties(prefix = "mvc.interceptor")
@Data
public class xxx{
# pojo代码,接收yml中mvc.interceptor定义的值
private boolean show = true;
private String info;
}
2.2定制拦截器
实现HandlerInterceptor#preHandle,对yml中定义的ShowProperties属性类进行判断或逻辑检验
public class ShowInfoInterceptor implements HandlerInterceptor {
@Autowired
private ShowProperties showProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (showProperties.isShow()) {
//拦截执行逻辑
if (StringUtils.hasText(showProperties.getInfo())) {
System.out.println(showProperties.getInfo());
} else {
System.out.println("Hello..");
}
}
return true;
}
}
2.3定义配置拦截器
实现WebMvcConfigurer#addInterceptors,把拦截器配上
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public ShowProperties showProperties() {
return new ShowProperties();
}
@Bean
public ShowInfoInterceptor showInfoInterceptor() {
return new ShowInfoInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(showInfoInterceptor())
.addPathPatterns("/**");
}
}
2.4配置starter入口启动类
@ConditionalOnProperty(name = "mvc.interceptor.show", matchIfMissing = false)
@ComponentScan("com.ldl")
@Configuration
public class ShowInfoAutoConfig {
}
2.5配置启动器的入口
在resource下面新建META-INF/spring.factories
填入内容
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ldl.config.ShowInfoAutoConfig
3.使用starter
1.引入打包
<dependency>
<groupId>org.ldl</groupId>
<artifactId>show-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2.yml中写入
mvc:
interceptor:
info: 1312312
show: true
3.调用api,观察效果(狗头)