簡體   English   中英

如何在spring配置類中創建RestControllerAdvice類型的spring @bean

[英]How to create spring @bean of type RestControllerAdvice in spring configuration class

我正在嘗試編寫 RestControllerAdvice,它是一個通用庫的一部分,我希望在某個屬性的當前可用。 根據我們的公共庫,我們通過配置而不是注釋來定義所有 bean,以便我們可以按需導入該配置類,而不是總是創建這些 bean。 但是我發現很難提到 bean 實際上是 Spring 配置類中的 RestControllerAdvice 類型。

下面是我的 RestControllerAdvice。 我從這個 ExceptionHandler 中刪除了@RestControllerAdvice否則無論如何都會創建這個 bean,在我的配置類中我添加了@AliasFor(annotation = RestControllerAdvice.class)但我不確定它是否是正確的方法,它也不起作用。

@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHandler {


    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<Void> handleMyException(CustomException e) {
        return new ResponseEntity(new UnauthorizedResponse().withMessage(e.getMessage()).withStatus(HttpStatus.UNAUTHORIZED.value()), null, HttpStatus.UNAUTHORIZED);
    }

}


@Configuration
public class ServiceCommonConfiguration {

    @Bean
    @AliasFor(annotation = RestControllerAdvice.class)
    @ConditionalOnProperty(name = PROPERTY, havingValue = "enable")
    public ExceptionHandler serviceCommonExceptionHandler() {
        return new ExceptionHandler();
    }
}

請試試這個:

@Configuration
public class ServiceCommonConfiguration {

    @RestControllerAdvice
    @ConditionalOnProperty(name = PROPERTY, havingValue = "enable")
    private class SpecificExceptionHandler extends ExceptionHandler {
      // Extends 'ExceptionHandler' class in your question.
    }
}

Spring 可以從內部類創建 bean,據我測試,甚至可以成功創建private和非靜態類的實例。

當然,您可以通過使用@Import來使用這個配置類,如下所示。

@Configuration
@Import(ServiceCommonConfiguration.class)
public class SomeUserOfLibraryConfiguration {.... 

當您既不導入配置類也不使 Spring 組件掃描類的包時,則不會創建異常處理程序的 bean。

筆記

  • @RestControllerAdvice / @ControllerAdvice注解只能在類級別使用,不能在方法級別使用。 因此,您需要聲明一個類並使用其中一個來注釋該類。

  • @AliasFor注釋,正如其 javadoc 所說,“用於聲明注釋屬性的別名”( @RestControllerAdvice的源代碼就是一個很好的例子)。 所以,我認為@AliasFor(annotation = RestControllerAdvice.class)在你上面的源代碼中什么都不做。

也可以看看

Spring 框架文檔核心技術 - 1.3.2。 實例化 Bean

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM