前言
Srping自动装配非常实用,我们可以利用这个把项目解耦合,真正使用的只需引入即可使用。
今天我们来演示下自动装配,利用自动装配,实现web拦截器,解析request中的内容。
项目搭建
引入需要的pom
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.20</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
编写拦截器
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author sxt
* @date 2022-07-01
* @describe header拦截器
*/
public class HeaderInterceptor implements HandlerInterceptor {
private final static String OPTIONS = "OPTIONS";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理request");
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("后置处理");
}
}
web配置
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author sxt
* @date 2022-07-01
* @describe web配置
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HeaderInterceptor());
}
}
自动装配配置类
import com.yqsl.config.header.WebConfig;
import org.springframework.context.annotation.Import;
/**
* @author sxt
* @date 2022-07-01
* @describe 自动配置
*/
@Import(WebConfig.class)
public class HeaderAutoConfiguration {
}
在/resource/META-INF/spring.factories中添加类路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.yqsl.config.HeaderAutoConfiguration
上传jar包
此时需要注意,直接打包有可能打包失败,需要把pom中内容删掉
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
打成jar包,上传到云仓库中,项目引入对应jar,就可以直接使用了。
网友评论