Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowired @Lazy

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

    }

}
like image 921
DD. Avatar asked Mar 14 '12 10:03

DD.


People also ask

What is @lazy annotation in Spring?

@Lazy annotation indicates whether a bean is to be lazily initialized. It can be used on @Component and @Bean definitions. A @Lazy bean is not initialized until referenced by another bean or explicitly retrieved from BeanFactory . Beans that are not annotated with @Lazy are initialized eagerly.

What will be happen when @lazy is used with @autowired?

Lazy Initialize @Autowired Dependency The Person bean will be created eagerly. But the autowired Address bean is annotated with the @Lazy annotation, which tells the spring container to initialize the bean only when it's first requested.

What is @lazy java?

The concept of delaying the loading of an object until one needs it is known as lazy loading. In other words, it is the process of delaying the process of instantiating the class until required.

How do I enable lazy initiation for a bean in Spring IOC?

To enable lazy loading for specific beans, use lazy-init=”true” attribute on bean definitions in bean configuration xml files.


1 Answers

Try

@Lazy @Autowired Long lazyParent;
like image 100
Bochu Avatar answered Oct 22 '22 12:10

Bochu