春天@Autowired @Lazy

DD.*_*DD. 9 java spring annotations lazy-loading

我正在使用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;
    }

}
Run Code Online (Sandbox Code Playgroud)
@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+"!";
    }
}
Run Code Online (Sandbox Code Playgroud)
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);

    }

}
Run Code Online (Sandbox Code Playgroud)

ska*_*man 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() + "!";
    }
}
Run Code Online (Sandbox Code Playgroud)

PS我希望你不是字符串,双打和长片定义为bean,这只是一个例子.对...?

  • Void Bean统治它们.Void Bean找到它们.Void Bean将它们全部带入,并在依赖注入中绑定它们 (6认同)
  • 我刚刚看到了一个'虚空'豆的可怕视野.一个用于TDWTF我认为...... (3认同)