簡體   English   中英

Spring:獲取注入一個bean的bean列表

[英]Spring: Get the list of beans injected into a bean

我正在尋找一種方法來列出在運行時注入到特定 Spring bean 中的 bean。 例如,給定這兩個類:

@Controller
public class TestController {

    @Autowired
    private TestComponent testComponent;

    private final TestService testService;

    public TestController(TestService testService) {
        this.testService = testService;
    }
}

@Service
public class TestService {

}

@Component
public class TestComponent {

}

TestController類的 bean 列表應該返回:

  • TestService (通過構造函數注入)
  • TestComponent (通過@Autowired注解注入)

是否存在可以為我返回此信息的現有 Spring 幫助程序/實用程序?

您可以使用方法getDependenciesForBean()ConfigurableBeanFactory查詢給定 bean 名稱的依賴 bean 的名稱。 所以在你的例子中,代碼可能看起來像

try (ConfigurableApplicationContext app = SpringApplication.run(MySpringApplication.class)) {
    ConfigurableListableBeanFactory beanFactory = app.getBeanFactory();
    String[] dependencies = beanFactory.getDependenciesForBean("testController");
    System.out.println(Arrays.toString(dependencies)); // [testService, testComponent]
}

這里的問題是您只處理 bean 的名稱 因此,要使給定 bean 實例的代碼通用,您必須找出 bean 的名稱(可以是非唯一的),並且在為這些名稱獲取實際注入的 bean 時,您可能不知道獲得相同的實例(因為 bean 定義上的@Scope(SCOPE_PROTOTYPE) )。

暫無
暫無

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

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