Home  >  Spring Core

Example of @Lazy in Spring

By Arvind Rai, April 04, 2013
@Lazy Annotation in spring is used with @Configuration. The bean which has been declared with @Lazy annotation will not be initialized by spring container. @Lazy will be initialized by container only when that bean will be accessed somewhere in code. Find the example.
AppConf.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class AppConf {
	@Bean
	@Lazy(value = true)
	public A a(){
		return new A();
	}
	@Bean	
	public B b(){
		return new B();
	}
} 




A.java
package com.concretepage;
public class A {
	public A(){
		System.out.println("class A initialized.");
	}
} 

B.java
package com.concretepage;
public class B {
	public B(){
		System.out.println("class B initialized.");
	}
} 

LazyTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class LazyTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		//Class B will be initialized
		ctx.register(AppConf.class);
		ctx.refresh();
		//Class A will be initialized
		ctx.getBean(A.class);
	}
} 

Output
class B initialized.
class A initialized. 
Find the link for XML Example of lazy-init in Spring
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us