Implement a custom spring boot starter

Everyone knows that spring boot integrates almost all spring class libraries, through its core spring-boot-autoconfigure module, combined with a series of starters to complete various xml and dependent jar tasks that originally required developers to configure. According to their own needs, personnel only need to introduce the specified starter.

Let's implement a custom spring boot starter. The main function is to intercept all controller requests and print out request parameters and header information.

I saw that many people on the Internet split into two modules, the autoconfigure module and the starter module. The example I gave here only contains the starter module.

First create a maven project
. Create a new META-INF directory under the resources directory, and create a new spring.factories file in this directory, with the following content:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.huang.AutoInitConfigurer,\
com.huang.CustomWebConfigurer

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ is fixed, the other is to look at the requirements, I have defined two @Configuration here

AutoInitConfigurer.java

@Configuration
public class AutoInitConfigurer {
    
    

    @Bean
    @ConditionalOnMissingBean
    public LogInterceptor1 logInterceptor1() {
    
    
        return new LogInterceptor1();
    }

}

CustomWebConfigurer.java

@Configuration
public class CustomWebConfigurer extends WebMvcConfigurerAdapter {
    
    

    private final LogInterceptor1 logInterceptor1;

    @Autowired
    public CustomWebConfigurer(LogInterceptor1 logInterceptor1) {
    
    
        this.logInterceptor1 = logInterceptor1;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(logInterceptor1);
        super.addInterceptors(registry);
    }
}

Define an interceptor to intercept all controller requests

@Slf4j
public class LogInterceptor1 extends HandlerInterceptorAdapter {
    
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    
    
        String requestParams = getQueryString(request.getParameterMap());
        String headers = getHeaderStr(request);

        log.info("request params = {} header = {}", requestParams, headers);

        return true;
    }

    public static String getHeaderStr(HttpServletRequest request) {
    
    
        try {
    
    
            StringBuilder sb = new StringBuilder(256);
            Enumeration e = request.getHeaderNames();

            while(e.hasMoreElements()) {
    
    
                String name = (String)e.nextElement();
                Enumeration headerValues = request.getHeaders(name);

                while(headerValues.hasMoreElements()) {
    
    
                    sb.append(name).append("=").append((String)headerValues.nextElement()).append("&");
                }
            }


            return sb.toString();
        } catch (Exception e) {
    
    
            return "";
        }
    }

    public static String getQueryString(Map<String, String[]> params) {
    
    
        try {
    
    
            StringBuilder sb = new StringBuilder(256);
            if (params != null && !params.isEmpty()) {
    
    
                params.keySet().stream().forEach((key) -> sb.append(key).append("=").append(params.get(key)[0]).append("&"));
                sb.deleteCharAt(sb.length() - 1);
            }

            return sb.toString();
        } catch (Exception e) {
    
    
            return "";
        }
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.huang</groupId>
  <artifactId>log-spring-boot-starter</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0-SNAPSHOT</version>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.12.RELEASE</version>
    <relativePath/>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-test</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>*.yml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>false</filtering>
        <includes>
          <include>*.yml</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Finally, it is marked as a jar package and uploaded to the maven warehouse.

Well, in our development project, we only need to rely on this jar, define a WebMvcConfigurerAdapter class, and register the LogInterceptor1 interceptor defined above to realize the log printing function.

The pom.xml dependencies are as follows:

 <dependency>
    <groupId>com.huang</groupId>
    <artifactId>log-spring-boot-starter</artifactId>
    <version>1.0.0-SNAPSHOT</version>
 </dependency>

Define the CustomWebAppConfigurer class

@Configuration
@Slf4j
public class CustomWebAppConfigurer extends WebMvcConfigurerAdapter {
    
    

    @Autowired
    private LogInterceptor1 logInterceptor1;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(logInterceptor1).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/huangdi1309/article/details/106267269