@Lazy使用说明
- 一般情况下,Spring容器在启动时会创建所有的Bean对象,使用@Lazy注解可以将Bean对象的创建延迟到第一次使用Bean的时候
使用方法
1、@Lazy(value = true):默认为true,不执行构造方法
2、@Lazy(value = false):执行构造方法
将bean加载搭到spring容器的方式
- @Configuration +@bean
@Configuration
public class BeanConfig {@Bean@Lazy(value = true)public People people() {return new People();}
}
- @component
@Component
@Lazy(value = true)
public class Cat{public Cat() {System.out.println("#######小白猫#######);}
}
- @import
@Import(value = {Dog.class})@Lazy(value=false)
public class Dog{public Dog() {System.out.println("#######大黄狗#######);}
}
示例代码
1、不使用@lazy
/*** @author shuliangzhao* @Title: MyLazy* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/10/10 19:27*/
@Component
public class MyLazy {public MyLazy() {System.out.println("懒加载...");}public void say() {System.out.println("say...");}
}
/*** @author shuliangzhao* @Title: LazyTest* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/10/10 19:31*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class LazyTest {@Autowiredprivate MyLazy myLazy;@Testpublic void test() {myLazy.say();}
}
执行结果:

2、使用lazy
/*** @author shuliangzhao* @Title: MyLazy* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/10/10 19:27*/
@Component
@Lazy
public class MyLazy {public MyLazy() {System.out.println("懒加载...");}public void say() {System.out.println("say...");}
}
/*** @author shuliangzhao* @Title: LazyTest* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/10/10 19:31*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class LazyTest {@Autowiredprivate MyLazy myLazy;@Testpublic void test() {myLazy.say();}
}
执行结果:
