我正在使用 Spring 注释,并且我想使用延迟初始化。
我遇到了一个问题,当我想从另一个类导入 bean 时,我被迫使用@Autowired
这似乎没有使用惰性初始化。有没有办法强制这种懒惰的初始化行为?
在这个例子中,我不想看到“正在加载父bean”被打印,因为我只是加载childBean
它不依赖于lazyParent
.
@Configuration
public class ConfigParent {
@Bean
@Lazy
public Long lazyParent(){
System.out.println("Loading parent bean");
return 123L;
}
}
@Configuration
@Import(ConfigParent.class)
public class ConfigChild {
private @Autowired Long lazyParent;
@Bean
public Double childBean() {
System.out.println("loading child bean");
return 1.0;
}
@Bean
@Lazy
public String lazyBean() {
return lazyParent+"!";
}
}
public class ConfigTester {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigChild.class);
Double childBean=ctx.getBean(Double.class);
System.out.println(childBean);
}
}
因为你正在使用@Autowired Long lazyParent
,Spring 将在上下文启动时解决该依赖关系。事实是lazyBean
is @Lazy
是无关紧要的。
尝试这个作为替代方案,尽管我不是 100% 相信这会像你想要的那样工作:
@Configuration
@Import(ConfigParent.class)
public class ConfigChild {
private @Autowired ConfigParent configParent;
@Bean
public Double childBean() {
System.out.println("loading child bean");
return 1.0;
}
@Bean
@Lazy
public String lazyBean() {
return configParent.lazyParent() + "!";
}
}
附:我希望你不是really将 Strings、Doubles 和 Longs 定义为 beans,这只是一个示例。正确的...?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)