簡體   English   中英

SpringBoot獲取應用的@RestController列表即List<@RestController>

[英]SpringBoot get the list of @RestController i.e List<@RestController> of the application

關於 SpringBoot 應用程序的小問題,以及如何獲取用@RestController注釋的類列表。

我有一個簡單的 SpringBoot 應用程序,其中有幾個我自己的@RestController ,例如:

@RestController
public class PersonController {

@RestController
public class OrderController {

@RestController
public class PriceController {

但是我也有我的依賴項,在我無法控制的第三方庫中,還有一些@RestController

在我的應用程序中,我想獲取所有@RestController的列表,即所有用注釋@RestController注釋的類。 類似List<@RestController>的東西,請注意 @ 符號,它不是List<RestController>

到目前為止,我嘗試的是使用通用接口擴展我的所有@RestController ,並獲取List<MyAtRestController> ,但此解決方案將僅限於我可以控制的@RestController 許多都在第三方依賴項中。

問題,請問如何從 SpringBoot 獲取@RestController List<@RestController>的列表?

謝謝

正如@Andrey B. Panfilov評論中指出的那樣,您可以在任何 Bean 中注入ApplicationContext並使用方法getBeansWithAnnotation()來檢索具有在上下文中注冊的特定注釋的 bean。

例子:

@Component          // or any other steriotype annotaion
@AllArgsConstructor // to make use of the constractor injection
public class MyBean {
    
    private ApplicationContext context;

    public Collection<Object> getRestControllers() {
    
        Collection<Object> controllers = context
            .getBeansWithAnnotation(RestController.class)
            .values();
        
        return controllers
    }
}

暫無
暫無

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

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