Spring @Autowired @Lazy

≡放荡痞女 提交于 2020-01-02 01:55:06

问题


I'm using Spring annotations and I want to use lazy initialization.

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?

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.

@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);

    }

}

回答1:


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.

Try this as an alternative, although I'm not 100% convinced this wil lwork as you want it to:

@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 really defining Strings, Doubles and Longs as beans, and that this is just an example. Right...?




回答2:


Try

@Lazy @Autowired Long lazyParent;


来源:https://stackoverflow.com/questions/9700338/spring-autowired-lazy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!