DEV Community

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

Posted on

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

Top comments (0)