spring boot 拦截器中无法注入serivce

另一篇简洁的方法:spring boot 拦截器中无法注入 serivce,autowired 失败

 

本文关键点为,在判断 OperatorLogService 注入失败的情况下,重新请求赋值;

BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
operatorLogService = (OperatorLogService) factory.getBean("operatorLogService"); 

在SpringBoot应用中获取应用上下文ApplicationContext方法

以下内容为转载:

摘要
最近在项目中用拦截器去拦截用户操作,并对操作日志进行记录, 在拦截器中记录日志时调用service 层 的save方法,发现service为null ,通过 @Autowired private LogService logService;这种方式无法注入;解决办法看以下代码。

@Configuration 
public class OptPermissionHandlerInterceptor extends HandlerInterceptorAdapter { 
  private Logger logger = LoggerFactory.getLogger(OptPermissionHandlerInterceptor.class); 
 
  @Autowired 
  private OperatorLogService operatorLogService; //这里使用@Autowired无法注入成功 
 
  @Override 
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws      Exception { 
        if (true) { 
            return true; 
        } else { 
            String result = "当前登录用户无权限!"; 
            response.getOutputStream().write(result.getBytes()); 
            response.setStatus(HttpStatus.OK.value()); 
            return false; 
        } 
  } 
 
  @SuppressWarnings("rawtypes") 
  @Override 
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 
    try { 
      if (handler instanceof HandlerMethod) { 
           HandlerMethod handlerMethod = (HandlerMethod) handler; 
           String beanName = handlerMethod.getBean().getClass().toString(); 
           String methodName = handlerMethod.getMethod().getName(); 
           String uri = request.getRequestURI(); 
           String remoteAddr = request.getRemoteAddr(); 
           String sessionId = request.getSession().getId(); 
 
           OperatorLog optLog = new OperatorLog(); 
           optLog.setBeanName(beanName); 
           optLog.setMethodName(methodName); 
           optLog.setRemoteAddr(remoteAddr); 
           optLog.setSessionId(sessionId); 
           optLog.setUri(uri); 
 
      if (operatorLogService == null) {//解决service为null无法注入问题 
         System.out.println("operatorLogService is null!!!"); 
         BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
         operatorLogService = (OperatorLogService) factory.getBean("operatorLogService"); 
      } 
      operatorLogService.saveOperatorLog(optLog); 
     } 
   } catch (Exception e) { 
       logger.error("", e); 
   } 
  } 
  
  @Override 
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, 
      Exception ex) throws Exception {
 
  } 
 
}

————————————————
版权声明:本文为CSDN博主「yubinpll9110」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yubinpll9110/article/details/51820336

Spring Boot项目拦截器(Interceptor)通常用于对请求进行预处理或后处理。如果你在开发拦截器时遇到了注入的service为空的问题,可能是由以下几种情况导致的: 1. **依赖注入时机问题**:Spring框架的Bean默认是在应用上下文加载时创建的,如果拦截器的Service依赖在上下文创建之前就需要被注入,那么可能会出现service为空的情况。解决这个问题的一个方法是使用`@PostConstruct`注解标记一个初始化方法,在该方法调用service进行操作,这样可以确保在依赖注入之后进行相关操作。 2. **拦截器配置问题**:确保你的拦截器配置在了Spring Boot的配置类,并且使用了`@Component`或`@Configuration`注解。这样Spring才能扫描到拦截器类,并进行依赖注入。如果拦截器是在WebMvcConfigurer配置的,可以使用`addInterceptors`方法,并将拦截器实例放入到Spring管理的Bean。 3. **拦截器作用域问题**:Spring的单例模式默认是作用域为整个Spring应用上下文,如果拦截器是在Web层使用的,并且你使用的是基于Servlet的Web应用,那么确保拦截器的Service实例没有被错误地限定为某个特定的请求作用域(request scope),这通常会导致注入的Service为空。 下面是一个解决上述问题的通用示例: ```java @Component public class MyInterceptor implements HandlerInterceptor { @Autowired private MyService myService; @PostConstruct public void init() { // 在拦截器调用Service以确保注入已完成 myService.doSomething(); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 处理请求之前的逻辑 return true; } // 其他方法... } ``` 在Spring Boot配置类注册拦截器: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } } ``` 确保在配置类或组件类上使用`@EnableWebMvc`或`@SpringBootApplication`注解,以便Spring能够扫描并管理拦截器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值