目录
一、过滤器调用service
二、方法1(失败)
三、方法2:手动获取bean(成功)
一、过滤器调用service
自定义的过滤器调用日志方法时发现service为null, 加@Component配置扫描依然不好使, 下面又做了几次尝试,记录下二、方法1(失败)
首先,自定义异常统一处理类, 然后,自定义异常DemoException, 最后,统一捕获处理,想法很好,但是此处无法抛出异常,十分尴尬。。。package com.sgcc.censor.common.base.exceptions; public class DemoException extends RuntimeException { private static final long serialVersionUID = -1004916162498956491L; public DemoException (String message) { super(message); } }package com.sgcc.censor.manage.exception; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.UnauthorizedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j @RestControllerAdvice public class ApplicationExceptionHandler { protected static final Logger logger = LoggerFactory.getLogger(ApplicationExceptionHandler.class); private final LogUtil logUtil; @Autowired public ApplicationExceptionHandler(LogUtil logUtil) { this.logSaveUtil = logSaveUtil; } @ExceptionHandler(MsgException.class) public BaseResponse msgException(Throwable t) { BaseResponse response = new BaseResponse(); LogParamDTO paramDTO = new LogParamDTO(); logUtil.saveLog(paramDTO); return response ; } }三、方法2:手动获取bean(成功)
shiro方法拦截器,建立一个全局拦截器MyPermissionAuthorizationFilter, 它继承了AuthorizationFilter,web应用启动的顺序是:listener->filter->servlet, 项目启动时, 先初始化listener,因此配置好的bean会被初始化和注入; 然后是filter的初始化; 最后才是dispathServlet的初始化, 因此,当我们需要在filter里注入一个注解的bean时,就会注入失败, 因为filter初始化时,注解的bean还没初始化,没法注入。import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component("springContextUtils") public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtils.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } public static Object getBean(Class> clz){ return applicationContext.getBean(clz); } }使用方法
LogSUtil bean = (LogUtil) SpringContextUtils.getBean(LogUtil.class); bean.saveLog(log);成功获取
有用请点赞,养成良好习惯!
疑问交流鼓励请留言!



