Home  >  Article  >  How to find where Spring @Bean is injected

How to find where Spring @Bean is injected

PHPz
PHPzforward
2024-02-09 08:30:20828browse

php editor Apple will introduce how to find the location of Spring @Bean injection. During the development process, we often need to use dependency injection to manage the creation and assembly of objects. The Spring framework provides the @Bean annotation to identify that the object returned by a method needs to be managed by the Spring container. But sometimes we may encounter a situation where we need to find the specific injection location. At this time, we need to use some techniques to locate the @Bean injection location. Next, we will share several methods to help you easily find the location of Spring @Bean injection.

Question content

I am configuring a Spring bean, for example:

@beans fun myService(): = MyService()

Is it possible to know where this bean will be injected?

I tried using BeanFactoryPostProcessor but there is no such possibility.

The only solution that comes to my mind is to loop through all the beans and check the constructor parameters via reflection. But if there are not multiple beans of the same type, the parameter names may differ from the bean names.

Solution

You can use the dependency detection interface

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(TestApplication.class, args);
        for (String bean: run.getBeanFactory().getDependentBeans("myService")) {
            System.out.println(bean);//the bean injected myService
        }
    }

}

The above is the detailed content of How to find where Spring @Bean is injected. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete