Java 春天@Autowired @Lazy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9700338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring @Autowired @Lazy
提问by DD.
I'm using Spring annotations and I want to use lazy initialization.
我正在使用 Spring 注释并且我想使用延迟初始化。
I'm running into a problem that when I want to import a bean from another class I am forced to use @Autowired
which does not seem to use lazy init. Is there anyway to force this lazy init behaviour?
我遇到了一个问题,当我想从另一个类导入一个 bean 时,我被迫使用@Autowired
它似乎没有使用惰性初始化。反正有没有强制这种懒惰的初始化行为?
In this example I do not want to see "Loading parent bean" ever being printed as I am only loading childBean
which has no dependencies on lazyParent
.
在这个例子中,我不希望看到“加载父 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);
}
}
采纳答案by skaffman
Because you're using @Autowired Long lazyParent
, Spring will resolve that dependency when the context starts up. The fact that lazyBean
is @Lazy
is irrelevent.
因为您使用的是@Autowired Long lazyParent
,Spring 将在上下文启动时解决该依赖项。这事实上lazyBean
是@Lazy
无关紧要,。
Try this as an alternative, although I'm not 100% convinced this wil lwork as you want it to:
试试这个作为替代方案,虽然我不是 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. I hope you're not reallydefining Strings, Doubles and Longs as beans, and that this is just an example. Right...?
PS 我希望你没有真正将字符串、双打和长整型定义为 bean,这只是一个例子。对...?
回答by Bochu
Try
尝试
@Lazy @Autowired Long lazyParent;