[英]Spring find beans that are not injected into other beans
I want to find all beans that are not injected into other beans, thus I can remove them to make spring start up faster.我想找到所有没有注入其他 bean 的 bean,因此我可以删除它们以使 spring 启动更快。 Any ideas?有任何想法吗? Thanks in advance.提前致谢。
From ConfigurableBeanFactory#getDependentBeans Javadoc , I see that there's a method we can invoke to get an array of beans that depends on the bean name we provide.从ConfigurableBeanFactory#getDependentBeans Javadoc中,我看到我们可以调用一个方法来获取依赖于我们提供的 bean 名称的 bean 数组。 Tracing backwards to how we can get the bean factory.回溯到我们如何获得 bean factory。 You could probably do the following if you can get a hold of the GenericApplicationContext
:如果您可以掌握GenericApplicationContext
,您可能会执行以下操作:
ConfigurableBeanFactory::getDependentBeans
to see if anything depends on it.调用ConfigurableBeanFactory::getDependentBeans
以查看是否有任何依赖它。@Component
public class Example {
@EventListener
public void contextRefreshed(ContextRefreshedEvent event) {
// Could also just autowire the context directly
GenericApplicationContext context = (GenericApplicationContext) event.getApplicationContext();
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
String[] beanNames = beanFactory.getBeanDefinitionNames();
for(String beanName : beanNames) {
String[] dependentBeanNames = beanFactory.getDependentBeans(beanName);
if (dependentBeanNames.length <= 0) {
// bean with nothing depending on it
}
}
}
}
Edit: This solution isn't perfect, but would probably be useful as a starting point.编辑:这个解决方案并不完美,但作为一个起点可能会很有用。 There are beans that could have nothing depend on it, but are used in the application.有些 bean 可能没有任何依赖,但在应用程序中使用。 A good example would be your controllers (classes annotated with @Controller
).一个很好的例子是你的控制器(用@Controller
注释的类)。 From what I tested out, it had 0 dependent beans but the request mapping methods it holds is clearly being executed and referenced somehow.根据我的测试,它有 0 个依赖 bean,但它所拥有的请求映射方法显然正在以某种方式执行和引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.