Home > Java > body text

How to find where Spring @Bean is injected

PHPz
Release: 2024-02-09 08:30:20
forward
786 people have browsed it

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
        }
    }

}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!