Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
@Lazy Instructions
- In general, Spring container will create all the objects Bean at startup, use @Lazy annotation can be created Bean object delayed until the first use of Bean
Instructions
1, @ Lazy (value = true ): Default is true, does not perform constructor
2, @ Lazy (value = false ): constructor is executed
Spring loaded to take the bean container manner
- @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("#######大黄狗#######);
}
}
Sample Code
1, do not use @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 {
@Autowired
private MyLazy myLazy;
@Test
public void test() {
myLazy.say();
}
}
The results:
2, using the 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 {
@Autowired
private MyLazy myLazy;
@Test
public void test() {
myLazy.say();
}
}
Results of the: