/java/

Dependency Injection with the Spring Framework. @Lazy bean initialization.

2015-02-15 20:36:20

If we create three bean without @Lazy annotation, they will be created almost immediately.

2015-02-15 20:21:01 INFO  BeanB:12 - initialization
2015-02-15 20:21:01 INFO  BeanA:19 - initialization
2015-02-15 20:21:01 INFO  BeanC:12 - initialization

We can change this behavior by adding @Lazy annotation.

2015-02-15 20:24:58 INFO  BeanC:12 - initialization
2015-02-15 20:25:01 INFO  BeanA:21 - initialization
2015-02-15 20:25:01 INFO  BeanB:14 - initialization

BeanA

package pl.btbw;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class BeanA {

    @Autowired
    private BeanB beanB;

    @Autowired
    private BeanC beanC;

    private final static Logger LOG = Logger.getLogger(BeanA.class);

    public BeanA() {
        LOG.info("initialization");
    }

}

BeanB

package pl.btbw;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class BeanB {

    private final static Logger LOG = Logger.getLogger(BeanB.class);

    public BeanB() {
        LOG.info("initialization");
    }
}

BeanC

package pl.btbw;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class BeanC {

    private final static Logger LOG = Logger.getLogger(BeanC.class);

    public BeanC() {
        LOG.info("initialization");
    }
}
package pl.btbw;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

    public static void main(String[] args) throws InterruptedException {

        ApplicationContext context
                = new ClassPathXmlApplicationContext("application-context.xml");

        Thread.sleep(3000);
        BeanA beanA = context.getBean("beanA", BeanA.class);

    }
}