springboot自定义starter

本文介绍了如何在SpringBoot应用中使用@ConfigurationProperties从YAML配置文件中读取属性,并通过HandlerInterceptor和WebMvcConfigurer自定义拦截器,实现按需显示信息的功能。还展示了如何通过starter方式集成和启用配置。
摘要由CSDN通过智能技术生成

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,观察效果(狗头)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值