其他分享
首页 > 其他分享> > 自制Spring-boot Starter

自制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);
        }
    
    }
    

标签:LogFilterRegistrationBean,Spring,void,boot,class,Starter,public,starter
来源: https://www.cnblogs.com/yourblog/p/16328827.html