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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:23:58  来源:igfitidea点击:

Spring @Autowired @Lazy

javaspringannotationslazy-loading

提问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 @Autowiredwhich 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 childBeanwhich 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 lazyBeanis @Lazyis 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;