Java Spring@Autowired@Lazy
我使用的是Spring注释,我想使用惰性初始化 我遇到了一个问题,当我想从另一个类导入bean时,我不得不使用Java Spring@Autowired@Lazy,java,spring,annotations,lazy-loading,Java,Spring,Annotations,Lazy Loading,我使用的是Spring注释,我想使用惰性初始化 我遇到了一个问题,当我想从另一个类导入bean时,我不得不使用@Autowired,它似乎不使用lazy init。是否存在强制这种惰性init行为的方法 在这个例子中,我不希望看到“加载父bean”被打印出来,因为我只加载childBean,它不依赖于lazyParent @Configuration public class ConfigParent { @Bean @Lazy public Long lazyParen
@Autowired
,它似乎不使用lazy init。是否存在强制这种惰性init行为的方法
在这个例子中,我不希望看到“加载父bean”被打印出来,因为我只加载childBean
,它不依赖于lazyParent
@Configuration
public class ConfigParent {
@Bean
@Lazy
public Long lazyParent(){
System.out.println("Loading parent bean");
return 123L;
}
}
因为您使用的是
@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() + "!";
}
}
另外,我希望你不是真的将字符串、双精度和长精度定义为bean,这只是一个例子。对吧…?试试看
@Lazy @Autowired Long lazyParent;
我刚刚看到了一个
Void
bean的可怕景象。一个是TDWTF,我认为…无效Bean来统治他们所有人。我想找到他们。voidbean将它们全部带来,并在依赖项注入绑定中them@skaffman我可以问一下为什么我不应该将字符串定义为bean吗?@wings因为String可以说是第二弱的类型(仅次于Object),这可能意味着您没有正确封装bean。
@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() + "!";
}
}
@Lazy @Autowired Long lazyParent;