【问题标题】:How to retrieve attribute from ControllerAdvice selector in ControllerAdvice class如何从 ControllerAdvice 类中的 ControllerAdvice 选择器中检索属性
【发布时间】:2017-12-19 08:07:46
【问题描述】:

我可以定义一个 Spring ControllerAdvice,它可以通过自定义注解被一部分控制器选择性地使用:

@RestController
@UseAdviceA
@RequestMapping("/myapi")
class ApiController {
 ...
}

@ControllerAdvice(annotations = UseAdviceA.class)
class AdviceA {

 ...
}

但是是否可以通过自定义注释传递属性,建议类可以从注释中获取?例如:

@RestController
@UseAdviceA("my.value")
@RequestMapping("/myapi")
class ApiController {
 ...
}

@ControllerAdvice(annotations = UseAdviceA.class)
class AdviceA {
 // Some way to get the string "myvalue" from the instance of UseAdviceA
 ...
}

任何其他实现相同结果的方法,即能够在可以传递给 ControllerAdvice 的 Controller 方法中定义自定义配置也将不胜感激。

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    这是一个解决方案。
    给定

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface UseAdviceA {
      public String myValue();
    }  
    

    控制器

    @RestController
    @UseAdviceA(myValue = "ApiController")
    @RequestMapping("/myapi")
    class ApiController {
     ...
    }
    

    你的控制器建议应该像

    @ControllerAdvice(annotations = {UseAdviceA.class})
    class AdviceA {
    
      @ExceptionHandler({SomeException.class})
      public ResponseEntity<String> handleSomeException(SomeException pe, HandlerMethod handlerMethod) {
        String value = handlerMethod.getMethod().getDeclaringClass().getAnnotation(UseAdviceA.class).myValue();
         //value will be ApiController
        return new ResponseEntity<>("SomeString", HttpStatus.BAD_REQUEST);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2020-11-15
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2022-10-14
      • 2018-01-15
      • 1970-01-01
      • 2018-12-12
      相关资源
      最近更新 更多