如何在Spring中使用@ComponentScan懒洋洋地加载所有的bean? [英] How to load all beans lazily with @ComponentScan in Spring?
问题描述
我正在使用基于Java的配置来设置我的Spring应用程序上下文:
I am using Java-based config to set up my Spring application context like this:
@Configuration
@Lazy
@ComponentScan(basePackageClasses = {MyProject.class, OtherProject.class})
public class MyAppConfig {
...
}
在配置中明确定义的Bean被懒惰地加载,就像你所期望的那样。但是,使用 @Named
注释的扫描类始终加载。如何解决这个问题?
Beans defined explicitly in the config are loaded lazily, like you would expect. However, scanned classes annotated with @Named
are always loaded eagerly. How can I solve this?
任何帮助都不胜感激。
请注意,对于 MyProject
包中的类,我可以通过使用 @Lazy
注释它们来解决此问题。但是另一个项目没有对Spring的依赖,我想保持它(因此 @Named
而不是 @Component
)。
Note that for classes in the MyProject
package, I can work around this by annotating them with @Lazy
as well. But the other project does not have a dependency to Spring and I want to keep it like that (hence @Named
and not @Component
).
还要注意,这不会在基于XML的配置中成为问题。在< beans>
标签接缝中设置 default-lazy-init =true
想要(虽然我没有测试过)。
Note also that this does not seam to be a problem in XML-based config. There, setting default-lazy-init="true"
in the <beans>
tag seams to do what I want (although I haven't tested that).
推荐答案
从版本4.1 RC2起,这个bug是固定的,你可以在组件扫描中完成延迟加载:
As of version 4.1 RC2, this bug is fixed, and you can accomplish lazy loading on component scan with:
@ComponentScan(basePackages = ["..."], lazyInit = true)
https://jira.spring.io/browse/SPR-10459
这篇关于如何在Spring中使用@ComponentScan懒洋洋地加载所有的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!