我有一个 ServiceA,它依赖于 ServiceB。 serviceB 来自带有 lazy-init=true 的 spring bean 文件,即,我只希望在我请求该 bean 时初始化 serviceB。
但是,我确实在整个应用程序中使用了 ServiceA,并且当我们进行基于 setter 的注入(inject)时,ServiceB 被初始化。
我希望 ServiceA 不初始化 ServiceB,直到调用 ServiceA 中需要 ServiceB 的任何方法。一种方法是使用方面但我一直在寻找最简单的解决方案,特别是在 serviceB 的 Spring XML 文件或 serviceB 中的某些注释或任何代理标志中。
最佳答案
我认为LazyInitTargetSource
做你需要的。
Useful when a proxy reference is needed on initialization but the actual target object should not be initialized until first use. When the target bean is defined in an ApplicationContext (or a BeanFactory that is eagerly pre-instantiating singleton beans) it must be marked as "lazy-init" too, else it will be instantiated by said ApplicationContext (or BeanFactory) on startup.
关于java - Spring DI - 不要初始化所有依赖的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121121/