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;


class PersonService {}

class PersonAnalyzer {}

class SimpleAnalyzer {}

class GeneralConfig {

    public SimpleAnalyzer simpleAnalyzer() {
        return new SimpleAnalyzer();

public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext =, args);

        List<Object> myBeans =
                .filter(beanName -> applicationContext.getBean(beanName).getClass().getPackage().getName().startsWith("com.omiu.demo"))
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)

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆