DEV Community

Cover image for Spring Boot: How to get only the beans I have explicitly created
Ovidiu Miu
Ovidiu Miu

Posted on

3

Spring Boot: How to get only the beans I have explicitly created

Problem: I need to get all the beans I have created explicitly in my app. When calling applicationContext.getBeanDefinitionNames() I get a list of bean names but a lot of them are not created explicitly by me but by Spring, and I'm not interested in those. There is no naming rule I can use for filtering at this point, because not all the beans injected by Spring start with "org.springframework"

Alt Text

Solution: Using applicationContext.getBeanDefinitionNames() and filtering the beans by my root package name ( This solution also works for other use cases, for example if I want to get all the beans I've defined under a certain package ).

package com.omiu.demo;

....

@Service
class PersonService {}

@Component
class PersonAnalyzer {}

class SimpleAnalyzer {}

@Configuration
class GeneralConfig {

    @Bean
    public SimpleAnalyzer simpleAnalyzer() {
        return new SimpleAnalyzer();
    }
}

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);

        List<Object> myBeans = Arrays.stream(applicationContext.getBeanDefinitionNames())
                .filter(beanName -> applicationContext.getBean(beanName).getClass().getPackage().getName().startsWith("com.omiu.demo"))
                .map(applicationContext::getBean)
                .collect(Collectors.toList());
    }
}
Enter fullscreen mode Exit fullscreen mode

This gives me a list of only 5 Beans, exactly those I'm interested in:
Alt Text

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay