二、方法1(失败)
首先,自定义异常统一处理类,
然后,自定义异常DemoException,
最后,统一捕获处理,想法很好,但是此处无法抛出异常,十分尴尬。。。
package com.sgcc.censor.common.base.exceptions;
/**
- @author java
*/
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;
/**
- @author java
*/
@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;
}
/**
* 异常详细信息
*
* @return BaseResponse
*/
@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 {
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtils.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
* 根据class获取对应的bean对象
* @param clz
* @return
*/
public static Object getBean(Class<?> clz){
return applicationContext.getBean(clz);
}
}