spring@Autowired @Lazy
我正在使用Spring注释,我想使用延迟初始化。
我遇到了一个问题,当我想从另一个类导入一个bean时,我被迫使用@Autowired
似乎没有使用lazy init。 反正有没有强制这种懒惰的初始化行为?
在这个例子中,我不希望看到“正在加载父bean”,因为我只加载了对lazyParent
没有依赖性的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
是@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() + "!"; } }
PS我希望你不是把字符串,双打和长片定义为bean,而这只是一个例子。 对…?
尝试
@Lazy @Autowired Long lazyParent;