Mark
Mark

Reputation: 5612

Spring: Get the list of beans injected into a bean

I'm looking for a way to list the beans that are injected into a particular Spring bean at runtime. For example, given these two classes:

@Controller
public class TestController {

    @Autowired
    private TestComponent testComponent;

    private final TestService testService;

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

and

@Service
public class TestService {

}

and

@Component
public class TestComponent {

}

The list of beans for the TestController class should return:

Is there an existing Spring helper/utility that can return this information for me?

Upvotes: 1

Views: 690

Answers (1)

Madjosz
Madjosz

Reputation: 529

You can query names of dependent beans from the ConfigurableBeanFactory for a given bean name with the method getDependenciesForBean(). So in your example the code could look like

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

The problem hereby is that you only work on names of beans. So to make the code generic for a given bean instance you would have to find out the name of the bean (which can be non-unique) and also when getting the actual injected beans for these names it can be possible that you don't get the same instances (because of @Scope(SCOPE_PROTOTYPE) on the bean definition).

Upvotes: 1

Related Questions