Filter和Intercepter中怎么获取Spring托管的bean对象

2024-03-28 06:52

本文主要是介绍Filter和Intercepter中怎么获取Spring托管的bean对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

怎么获取Spring托管的bean对象


文章目录

  • 怎么获取Spring托管的bean对象
  • 前言
  • 一、Filter中获取Spring托管的Bean对象
    • 1、原理
    • 2、实现方式
  • 二、Interceptor中获取Spring托管的Bean对象
    • 1、原理
    • 2、实现方式
  • 三、配置时通过构造方法的方式进行引入
  • 四、使用场景推荐
    • 1、 Filter的使用场景:
    • 2、Interceptor的使用场景:
    • 3、[官方文档](https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config-interceptors)
  • 总结


前言

为什么会写这篇文章?很简单,因为我踩坑了。先前在写一个功能的时候,需要写一个过滤器,然后在拦截请求过程中需要使用到redis,需要引入一个redis的bean,然后发现使用@Autowired和@Resource两个注解都使不了,然后我先整了一个方式就是在注册这个过滤器的时候把bean传进去,后面百度完之后就有了这篇文章。

在Spring框架中,Filter和Interceptor是两种常用的拦截请求的工具,用于在请求过程中执行特定的逻辑。然而,由于它们不属于Spring容器直接管理的Bean,所以在Filter和Interceptor中直接获取Spring托管的Bean对象可能会有些困难,不能直接通过注入注解来操作。本文将介绍如何在Filter和Interceptor中获取Spring托管的Bean对象,并通过案例和使用场景来帮助理解。


一、Filter中获取Spring托管的Bean对象

1、原理

Filter在Spring中通常不是由Spring容器直接管理的,而是由Servlet容器(如Tomcat)负责实例化和调用。因此,要在Filter中使用Spring托管的Bean,需要通过一些额外的方式来实现。

2、实现方式

一种常见的方式是通过实现Filter接口,并在初始化方法中使用SpringBeanAutowiringSupport类来实现自动装配。这个类是Spring提供的一个工具类,用于在非Spring管理的类中注入Spring Bean。

定义一个Spring托管的Bean,比如一个服务类(Service),下面示例中使用的都是这个MyService服务类作为例子。:

import org.springframework.stereotype.Service;  @Service  
public class MyService {  public String doSomething() {  return "Service method invoked";  }  
}

示例:

import org.springframework.beans.BeansException;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.ApplicationContextAware;  
import org.springframework.stereotype.Component;  
import org.springframework.web.filter.GenericFilterBean;  import javax.servlet.*;  
import java.io.IOException;  public class MyFilter extends GenericFilterBean {  @Autowired  private MyService myService; // 这里是无法直接注入的,需要通过其他方式实现  // ... 其他代码 ...  @Override  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  throws IOException, ServletException {  // 使用mySpringBean执行某些操作...  // 但由于上面的注入方式不起作用,我们需要通过ApplicationContext来获取Bean  chain.doFilter(request, response);  }  
}  @Component  
public class SpringContextUtil implements ApplicationContextAware {  private static ApplicationContext applicationContext;  @Override  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  SpringContextUtil.applicationContext = applicationContext;  }  public static <T> T getBean(Class<T> beanClass) {  return applicationContext.getBean(beanClass);  }  
}  // 修改后的MyFilter类  
public class MyFilter extends GenericFilterBean {  // ... 其他代码 ...  @Override  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  throws IOException, ServletException {  MyService myService = SpringContextUtil.getBean(MyService.class);  // 现在可以使用mySpringBean执行操作了...  chain.doFilter(request, response);  }  
}

过滤器还需要在配置类中进行配置才能生效,具体配置代码如下:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  @Configuration  
public class WebConfig implements WebMvcConfigurer {    @Beanpublic FilterRegistrationBean<MyFilter> platformFilter() {FilterRegistrationBean<MyFilter> filterRegBean = new FilterRegistrationBean<>();//设置过滤器filterRegBean.setFilter(new MyFilter());//设置过滤路径:所有请求路径filterRegBean.addUrlPatterns("/*");//设置过滤顺序:数字越小,会在越前面过滤filterRegBean.setOrder(-9999);return filterRegBean;}  
}

注意:上面的示例中,MyFilter类中的@Autowired注解实际上是不起作用的,因为MyFilter不是由Spring容器管理的。我们通过SpringContextUtil这个工具类来获取ApplicationContext,并进一步获取我们需要的Bean。

然而,这种方式并不是最佳实践。更好的做法是将Filter也交给Spring容器管理,这样就可以直接使用@Autowired注解进行注入了。这可以通过在配置类中声明Filter为Bean来实现,或者使用@Component注解并将Filter类放在Spring扫描的包中,这点可以参考下面内容。

二、Interceptor中获取Spring托管的Bean对象

1、原理

与Filter不同,Interceptor通常是作为Spring MVC框架的一部分来使用的,因此它们可以直接由Spring容器管理,并且可以直接使用@Autowired注解来注入Spring托管的Bean。

2、实现方式

在Interceptor中使用Spring托管的Bean非常简单,只需要在Interceptor类中添加相应的字段并使用@Autowired注解即可。

示例:

定义Interceptor,并使用@Autowired注解来注入上面定义的MyService:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.servlet.HandlerInterceptor;  
import org.springframework.web.servlet.ModelAndView;  import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  @Component  
public class MyInterceptor implements HandlerInterceptor {  @Autowired  private MyService myService;// 这里可以直接注入Spring托管的Bean对象    @Override  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {  // 在请求处理之前调用  String result = myService.doSomething(); // 使用MyService的方法  // 可以将result存储到request属性中,供后续使用  request.setAttribute("serviceResult", result);  return true; // 返回true表示继续处理请求  }  @Override  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {  // 在请求处理之后}  @Override  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {  // 在整个请求完成之后调用}  
}

拦截器还需要在配置类中进行配置才能生效,具体配置代码如下:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  @Configuration  
public class WebConfig implements WebMvcConfigurer {  @Autowired  private MyInterceptor myInterceptor; // 注入MyInterceptor Bean  @Override  public void addInterceptors(InterceptorRegistry registry) {  registry.addInterceptor(myInterceptor)  .addPathPatterns("/**"); // 拦截所有路径的请求  }  
}

三、配置时通过构造方法的方式进行引入

也就是前言中我个人使用的一个方式。

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Component;  
import org.springframework.web.servlet.HandlerInterceptor;  import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  public class MyInterceptor implements HandlerInterceptor {  private final MyService myService;  public MyInterceptor(MyService myService) {  this.myService = myService;  }  @Override  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {  // 在请求处理之前调用  String result = myService.doSomething(); // 使用MyService的方法  // 可以将result存储到request属性中,供后续使用  request.setAttribute("serviceResult", result);  return true; // 返回true表示继续处理请求  }  // postHandle和afterCompletion方法可以根据需要实现  
}import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  @Configuration  
public class WebConfig implements WebMvcConfigurer {  @Resourceprivate MyService myService;@Override  public void addInterceptors(InterceptorRegistry registry) {  registry.addInterceptor(new MyInterceptor(myService))  .addPathPatterns("/**"); // 拦截所有路径的请求  }  
}

四、使用场景推荐

1、 Filter的使用场景:

  1. 跨域处理:在Filter中设置响应头,实现跨域请求的支持。
  2. 日志记录:记录请求和响应的详细信息,用于监控和调试。
  3. 编码设置:统一设置请求和响应的字符编码,避免乱码问题。

2、Interceptor的使用场景:

  1. 权限验证:在请求处理之前进行用户身份验证和权限检查。
  2. 数据绑定:根据请求参数或会话信息,在请求处理之前进行数据绑定或预处理。
  3. 异常处理:捕获并处理请求处理过程中发生的异常,提供友好的错误响应。

3、官方文档


总结

在SpringBoot开发中,Interceptor和Filter都不能直接通过Spring的依赖注入机制,即@Autowired或者@Resource这两个注解,直接注入相关的Bean,都需要采取额外的手段才能够去获取Bean。而想要直接利用Spring的依赖注入机制来直接注入的话,那么需要通过使用@Component、@Service、@Repository或@Controller等注解(其实@Service、@Repository、@Controller都是复合型注解,其中包括了@Component注解,也是真正起作用的注解,所以直接使用@Component即可。)来实现Spring对Bean的托管。

这篇关于Filter和Intercepter中怎么获取Spring托管的bean对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/854803

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏