我使用的是Spring注释,我想使用延迟初始化。
我遇到了一个问题,当我想从另一个类导入bean时,我被迫使用@Autowired
,它似乎没有使用lazy init。反正有没有强制这种懒惰的初始化行为?
在这个例子中,我不想看到"加载父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);
}
}
答案 0 :(得分:13)
因为您正在使用@Autowired Long lazyParent
,所以Spring会在上下文启动时解析该依赖项。 lazyBean
为@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() + "!";
}
}
P.S。我希望你不是真的将字符串,双打和长片定义为bean,这只是一个例子。右...?
答案 1 :(得分:1)
尝试
@Lazy @Autowired Long lazyParent;