自制Spring-boot Starter

  1. 新建Spring boot项目

    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.0</version>
      <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>web-filter-log-boot-starter</artifactId>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  2. 定义一个web过滤器,验证Spring boot starter是否生效

    // Filter
    public class LogFilter implements Filter {
    
        private Logger logger = LoggerFactory.getLogger(LogFilter.class);
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            System.err.println("logFilter init...");
            logger.info("logFilter init...");
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            logger.info("uri: {} is working.", httpServletRequest.getRequestURI());
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
            logger.info("logFilter destroy...");
        }
    }
    
    // 配置Filter生效
    public class LogFilterRegistrationBean extends FilterRegistrationBean<LogFilter> {
        public LogFilterRegistrationBean() {
            super();
            this.setFilter(new LogFilter());
            this.addUrlPatterns("/*");
            this.setName("LogFilter");
            this.setOrder(1);
        }
    }
    

    定义自动配置类

    // 自动配置类
    @Configuration
    @ConditionalOnClass({LogFilterRegistrationBean.class, LogFilter.class})
    public class LogFilterAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean(LogFilterRegistrationBean.class)
        public LogFilterRegistrationBean logFilterRegistrationBean() {
            return new LogFilterRegistrationBean();
        }
    }
    
  3. 定义注解,使用注解将使该starter配置生效

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Import(EnableLogFilterImportSelector.class)
    public @interface EnableLogFilter {
    
    }
    
  4. 定义EnableLogFilterImportSelector用于从spring.factories加载starter自动配置类

    public class EnableLogFilterImportSelector implements DeferredImportSelector, BeanClassLoaderAware, EnvironmentAware {
    
        private ClassLoader beanClassLoader;
        private Class annotationClass = EnableLogFilter.class;
    
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    
            var attributes =
                    AnnotationAttributes.fromMap(importingClassMetadata
                            .getAnnotationAttributes(annotationClass.getName(), true));
            List<String> factories = new ArrayList<>(
                    new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(this.annotationClass, this.beanClassLoader)));
            return factories.toArray(new String[factories.size()]);
        }
    
        @Override
        public void setEnvironment(Environment environment) {
    
        }
    
        @Override
        public void setBeanClassLoader(ClassLoader classLoader) {
            this.beanClassLoader = classLoader;
        }
    }
    
  5. 在resources/META-INF中添加spring.factories

    com.example.annotation.EnableLogFilter=com.example.config.LogFilterAutoConfiguration
    
  6. 使用starter

    <dependency>
      <groupId>com.example</groupId>
      <artifactId>web-filter-log-boot-starter</artifactId>
    </dependency>
    

    在启动类上添加EnableLogFilter注解,使starter自动配置生效

    @SpringBootApplication
    @EnableLogFilter
    public class DemoBootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoBootApplication.class, args);
        }
    
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值