【问题标题】:Using ControllerAdvice from external jar使用外部 jar 中的 ControllerAdvice
【发布时间】:2019-07-27 15:11:10
【问题描述】:

我正在尝试创建可供多个模块使用的异常处理模块。所以我创建了一个包含所有与处理异常相关的逻辑的 jar。我正在尝试添加可以捕获异常并生成错误响应的全局控制器建议。问题是该控制器建议没有被调用。 当我在各个模块中编写声明此控制器建议时,它工作正常。

异常处理模块 --ExceptionToResponseGenerator 主模块 --RestController 这不起作用

异常处理模块

主模块 --RestController --ExceptionToResponseGenerator 这行得通

我做错了什么?


package com.abc.cde.exceptionhandler.handler;

@ControllerAdvice
@Log
public class ExceptionToResponseGenerator extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders httpHeaders, HttpStatus httpStatus, WebRequest webRequest) {
        return new ResponseEntity(new ErrorDetails(new Date(), "bad", "bad"), HttpStatus.BAD_REQUEST);
    }

主类

    @Import(IncludeExceptionHandling.class)
   @SpringBootApplication
   public class MainApplication{

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }


}

-----------
IncludeExceptionHandling

@Configuration
@EnableAspectJAutoProxy
public class IncludeExceptionHandling {

    @Bean
    public ExceptionLoggerPointcut notifyAspect() {
        return new ExceptionLoggerPointcut();
    }
}

ExceptionLoggerPointcut 是 aop 包装异常并重新抛出它

【问题讨论】:

  • 带有包名的邮政编码,包括你的主类的包名,用@SpringBootApplication注解
  • @Strelok 编辑了我的帖子
  • 你没有发布你的主类的包。 ExceptionToResponseGenerator 应该在 MainApplication 类所在包的子包中,否则不会被自动扫描。

标签: spring-boot exception


【解决方案1】:

问题似乎在于缺少@ComponentScan。请将您的代码的包名和外部 jar 库名传递给 @ComponentScan 注解,以便 Spring 可以注册组件并使它们可用于您的应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-10
    • 2012-01-18
    • 2012-04-24
    • 1970-01-01
    • 2014-12-20
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多