Is there a way to see which Beans were registered through component scanning?

Viewed 81

I'm trying to determine which beans are picked up by the Spring Boot component scanning mechanism vs which are picked up by auto-configuration etc. Have not been able to find a way to do this, is this possible?

I'd like to know this because I'm going to use the spring-context-indexer to create a META-INF/spring.components file in my application JAR. However, I pull in other libraries/jars and am wondering if this will break my app if those JARs provide beans that rely on component scanning to be registered.

1 Answers

I don't know if there's a nicer way to do this, but you could get some of that information through AnnotationConfigServletWebServerApplicationContext::getBeanDefinition (you can autowire the context).

// Bean from autoconfiguration
// Can check the factory bean name and see that it has 
// the "org.springframework.boot.autoconfigure" package
// to determine that it's probably from autoconfiguration
BeanDefinition autoConfigDef = context.getBeanDefinition("dispatcherServletRegistration");
autoConfigDef.getFactoryBeanName(); // org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
autoConfigDef.getFactoryMethodName(); // dispatcherServletRegistration

// Bean from my configuration @Bean + @Configuration
// If it has a factory bean name and it doesn't have the 
// Spring autoconfiguration package, it's probably from one of our
// own configurations
BeanDefinition myConfigDef = context.getBeanDefinition("myConverter");
myConfigDef.getFactoryBeanName(); // me.demo.MyConfiguration
myConfigDef.getFactoryBeanMethod(); // myConverter

// Bean annotated with @Component and discovered via component scan
// Doesn't have a configuration associated with it, so it was probably
// detected via the @Component annotation
BeanDefinition componentDef = context.getBeanDefinition("myController");
componentDef.getFactoryBeanName(); // null
componentDef.getFactoryBeanMethod(); // null

If others know cleaner methods, I would also love to know how.

Related