今天主要从以下几方面来介绍一下@Lazy注解
@Lazy注解是什么
@Lazy注解怎么使用
1,@Lazy注解是什么
@Lazy注解用于标识bean是否需要延迟加载,源码如下:
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
/**
* Whether lazy initialization should occur.
*/
boolean value() default true;
}
只有一个参数,默认是true,也就是说只要加了这个注解就会延迟加载
2,@Lazy注解怎么使用
没加注解之前主要容器启动就会实例化bean,如下:
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
创建user实例
而加上@Lazy注解则必须在第一次调用的时候才会加载如下:
/**
* 定义一个bean对象
* @return
*/
@Scope
@Lazy
@Bean(value="user0",name="user0",initMethod="initUser",destroyMethod="destroyUser")
public User getUser(){
System.out.println("创建user实例");
return new User("张三",26);
}
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
User bean2 = applicationContext2.getBean(User.class);
创建user实例
实例1 === User [userName=张三, age=26]
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦