![](/img/trans.png)
[英]Does Spring Java Configuration bean method calls get injected with managed beans at runtime?
[英]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.