Spring注解@Lazy
一、@Lazy注解
1、@Lazy注解作用
lazy 翻译过来是"懒惰的"
@Lazy(懒加载):该注解用于惰性加载初始化标注的类、方法和参数。
在Spring中常用于单实例Bean对象的创建和使用;
单实例Bean懒加载:容器启动后不创建对象,而是在第一次获取Bean创建对象时,初始化。
![在这里插入图片描述](https://img-blog.csdnimg.cn/9def2ecda6fa447dab883101e5d1cc79.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSn5qCR5LiL6Lqy6Zuo,size_19,color_FFFFFF,t_70,g_se,x_16)
2、@Lazy
可标注在类、方法、构造方法、参数、字段上
@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;
}
二、@Lazy案例
1、项目结构
![在这里插入图片描述](https://img-blog.csdnimg.cn/72587934a3bb4b90807c9eb249bbcc9f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSn5qCR5LiL6Lqy6Zuo,size_11,color_FFFFFF,t_70,g_se,x_16)
2、Persion
package com.dashu.bean;
public class Persion {
public Persion(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Persion{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3、Bean注册配置类
package com.dashu.config;
import com.dashu.bean.Persion;
import org.springframework.context.annotation.*;
/**
* @Configuration 注解:告诉Spring这是一个配置类
*
* 配置类 == 配置文件(beans.xml文件)
*
*/
@Configuration
public class BeanConfig {
@Lazy
@Bean
public Persion persion(){
System.out.println("初始化Persion...");
return new Persion("张三",20);
}
}
4、测试类
package com.dashu;
import com.dashu.bean.Persion;
import com.dashu.config.BeanConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
/**
* 只在第一次获取Bean时,初始化。之后的获取都是同一个对象
*/
Persion persion1 = (Persion) annotationConfigApplicationContext.getBean("persion");
Persion persion2 = annotationConfigApplicationContext.getBean(Persion.class);
System.out.println(persion1 == persion2);
}
}
5、测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/808c8c944bf14fa59499d4b345cfb8b2.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSn5qCR5LiL6Lqy6Zuo,size_20,color_FFFFFF,t_70,g_se,x_16)