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

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件