四、SpringBoot整合拦截器

本文详细介绍了如何在SpringBoot 2.0中整合拦截器,包括创建拦截器、注册拦截器及测试过程。通过实现HandlerInterceptor接口,演示了preHandle、postHandle和afterCompletion三个关键方法的自定义,并展示了如何在控制器中测试拦截器的效果。

本节我将带大家来学习一下springboot2.0中是如何整合拦截器。

我们需要引入的依赖依旧是springboot2.0父工程和web组件

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

编写我们的启动类Main

/**
 * @author 小吉
 * @description springboot启动类
 * @date 2020/5/23
 */
@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
}

1、创建拦截器

我们通过实现HandlerInterceptor接口来做我们的拦截器,可以查看到HandlerInterceptor接口源码,该接口定义的三个方法都使用default关键字修饰,这个是JDK8新增加的特性。被default关键字修饰的方法可以不实现,可以默认使用。那么我们来重新实现一下这三个方法。

HandlerInterceptor接口源码展示(已经去除注释):

public interface HandlerInterceptor {
	default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		return true;
	}
	default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
	}
	default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}

}

MyIntercept类源码

/**
 * @author 小吉
 * @description springboot2.0整合拦截器
 * @date 2020/5/23
 */
@Component
public class MyIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求执行之前拦截..." + System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求执行中..." + System.currentTimeMillis());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求执行完成..." + System.currentTimeMillis());
    }
}

2、注册拦截器

/**
 * @author 小吉
 * @description web配置
 * @date 2020/5/23
 */
@Configuration
public class WebConfig {
    @Autowired
    private MyIntercept myIntercept;
    
    @Bean
    public WebMvcConfigurer WebMvcConfigurer() {
        return new WebMvcConfigurer() {
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(myIntercept).addPathPatterns("/*");
            };
        };
    }
}

将MyIntercept拦截器注册到springboot的web配置中。

3、编写控制器测试

/**
 * @author 小吉
 * @description 测试拦截器拦截
 * @date 2020/5/23
 */
@RestController
public class HelloController {

    @RequestMapping("hello")
    public String hello(){
        System.out.println("进入hello方法..." + System.currentTimeMillis());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "进入hello方法";
    }

}
请求执行之前拦截...1590244547663
进入hello方法...1590244547671
请求执行中...1590244549691
请求执行完成...1590244549691
### 整合 Hibernate 拦截器Spring Boot 的方法 在 Spring Boot整合 Hibernate 拦截器可以用于实现自定义逻辑或审计功能。以下是具体的方法: #### 配置 `LocalSessionFactoryBean` 或 `EntityManagerFactory` 由于 Spring Boot 自动配置了 Hibernate,因此可以通过设置 `hibernate.session_factory.interceptor` 属性来指定拦截器类。 ```properties spring.jpa.properties.hibernate.session_factory.interceptor=com.example.CustomInterceptor ``` 此属性会告诉 Hibernate 使用哪个拦截器实例[^1]。 #### 创建自定义拦截器类 创建一个继承自 `org.hibernate.EmptyInterceptor` 的类,并重写所需的方法。例如: ```java import org.hibernate.EmptyInterceptor; import java.io.Serializable; public class CustomInterceptor extends EmptyInterceptor { @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { // 实现保存前的逻辑 System.out.println("Entity is being saved: " + entity); return super.onSave(entity, id, state, propertyNames, types); } @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { // 实现在删除之前的逻辑 System.out.println("Entity is being deleted: " + entity); super.onDelete(entity, id, state, propertyNames, types); } } ``` 上述代码展示了如何通过覆盖 `onSave` 和 `onDelete` 方法,在实体保存和删除之前执行特定操作。 #### 注册拦截器Spring 应用上下文中 如果需要动态注册拦截器,则可以在应用启动时将其注入到 Bean 定义中。例如: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DataSource dataSource) { Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.session_factory.interceptor", customInterceptor()); return builder.dataSource(dataSource).packages("com.example").persistenceUnit("unitName") .properties(properties).build(); } @Bean public CustomInterceptor customInterceptor() { return new CustomInterceptor(); } } ``` 这段代码显示了如何将拦截器作为 Bean 进行管理并传递给 `entityManagerFactory` 的配置过程[^2]。 #### 测试集成效果 完成以上步骤后,运行应用程序并通过调试验证拦截器是否按预期工作。每次触发数据库交互时,相应的拦截器方法会被调用。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值