有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Spring框架MVC中AOP的java实现

我正试图用Spring MVC实现一个RESTfulAPI。在我的应用程序中使用AOP Aspect时,我的编码出错了。我需要检查源代码的每个请求中的authToken,这样我就可以授予授权,还需要它来记录日志

在我的代码中,有几个custom exception classes是从另一个主customized exception class继承的,它是从Exception扩展而来的。当抛出自定义异常时,我需要等待异常的方法在我的方面类中工作,以便我可以返回适当的错误JSON响应

然而,在我的代码中,这两种等待异常的方法都有效,我想知道我是否以正确的方式编写了异常类。还有一件事,我不知道如何判断我的方面类不适用于我定义的某些操作

这是我的代码:

@Aspect
public class SowLoggerAOP {

    protected Logger logger = Logger.getLogger("SowLoggerAOP");
    @Autowired(required = true)
    private HttpServletRequest request;
    @Resource(name = "personService")
    private PersonService personService;

    @Pointcut("execution(* sow.webservice.controllers..*.*(..))")
    private void selectAll(){}

    @Before("execution( * sow.webservice.controllers.PersonController.*(..))")
    public void logBeforeReq(JoinPoint jp) throws Exception{
        String personId = request.getParameter(Consts.AUTH_TOKEN);
        if (personService.isUserValid(personId)) {
            logger.debug("Spring AOP! Before invocation SUCCESFULL!!!: ");
        }
        else {
            logger.error("Person not found for the " + Consts.AUTH_TOKEN + " : " + personId);
            throw new PersonNotFoundException(
                "Person not found for the " + Consts.AUTH_TOKEN + " : " + personId,
                ErrorCodes.PERSON_NOT_FOUND);
        }
    }

    @AfterThrowing(pointcut = "selectAll()", throwing = "sowEx")
    public SowResult throwingSowException(SowCustomException sowEx){
        int errorCode = ErrorCodes.GENERAL_SYSTEM_ERROR;
        if(sowEx.getErrorCode() != 0)
            errorCode = sowEx.getErrorCode();
        SowResult result = new SowResult(Consts.SOW_RESULT_ERROR,
                                         errorCode,
                                         sowEx.getMessage(),
                                         "islem hata almistir!!");

        System.out.println("There has been an exception: " + sowEx.toString());
        return result;
    }

    @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
    public void throwingJavaException(Exception ex){
        System.out.println("JAVA EXCEPTION IS THROWN :");
    }
}

public class SowCustomException extends Exception{

    private int errorCode;

    public SowCustomException(){
        super();
    }

    public SowCustomException(String errMsg){
        super(errMsg);
    }
    public SowCustomException(String errMsg, int errorCode){
        super(errMsg);
        this.errorCode = errorCode;
    }

    public SowCustomException(int errorCode){
        super();
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}
public class PersonNotFoundException extends SowCustomException{

    public PersonNotFoundException(){
        super();
    }

    public PersonNotFoundException(String errMsg){
        super(errMsg);
    }

    public PersonNotFoundException(String errMsg, int errorCode){
        super(errMsg);
        super.setErrorCode(errorCode);
    }

    public PersonNotFoundException(int errorCode){
        super();
        super.setErrorCode(errorCode);
    }
}

必须从该类创建预期的JSON:

public class SowResult {

    public int resultCode; // 1- Succesfull, 0- Fail
    public int errorCode;
    public String errorString;
    public String message;
    public Date date;
    public SowResult(int resultCode, int errorCode, String errorString,
            String message) {
        this.resultCode = resultCode;
        this.errorCode = errorCode; // 0 - No Error
        this.errorString = errorString;
        this.message = message;
        this.date = new Date();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    不幸的是,Spring的AOP堆栈忽略了来自@AfterThrowing通知方法的任何返回值。它只是执行它,然后继续抛出最初抛出的异常

    您可能希望使用@Around通知,将proceed调用包装在try-catch块中,生成SowResult并返回它

  2. # 2 楼答案

    正如Sotirios Delimanolis所说,如果您想在截获抛出异常的方法后返回某些内容,那么应该使用@Around。类似这样(我相信你的切入点是正确的):

    @Around("selectAll()")
       public Object handleException(ProceedingJoinPoint pjp) throws Throwable {
          int errorCode = ErrorCodes.GENERAL_SYSTEM_ERROR;
          if(sowEx.getErrorCode() != 0)
             errorCode = sowEx.getErrorCode();
          SowResult retVal = null;
    
          try {
             retVal = (SowResult) pjp.proceed();
          } catch (RequestValidationException sowEx) {
             //now return the error response
             return new SowResult(Consts.SOW_RESULT_ERROR,
                                         errorCode,
                                         sowEx.getMessage(),
                                         "islem hata almistir!!");
          }
    
      return retVal;
    }