如何在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 版本开始,此错误已修复,您可以通过以下方式完成组件扫描的延迟加载:
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屋!