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

怎么获取Spring托管的bean对象



前言

为什么会写这篇文章?很简单,因为我踩坑了。先前在写一个功能的时候,需要写一个过滤器,然后在拦截请求过程中需要使用到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 {    
  
    @Bean
    public 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 {  
   
	@Resource
	private 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的托管。

  • 18
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jz_Stu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值