免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
@Lazy手順
- 一般に、Springコンテナは、ビーンの最初の使用まで遅延@Lazy注釈を作成することができるBeanオブジェクトを、起動時にすべてのオブジェクトBeanを作成し使用します
使用
1、レイジー(値=真@ ): デフォルトはtrueで、コンストラクタを実行しません
レイジー(値= falseを@、2 ): コンストラクタが実行されます
春はBeanコンテナ方式を取るためにロードされました
- @Configuration + @豆
@Configuration
public class BeanConfig {
@Bean
@Lazy(value = true)
public People people() {
return new People();
}
}
- @成分
@Component
@Lazy(value = true)
public class Cat{
public Cat() {
System.out.println("#######小白猫#######);
}
}
- @インポート
@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 {
@Autowired
private MyLazy myLazy;
@Test
public void test() {
myLazy.say();
}
}
結果:
2、怠惰を使用して
/**
* @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();
}
}
結果: