Spring注解@Lazy

Spring注解@Lazy

一、@Lazy注解

1、@Lazy注解作用

lazy 翻译过来是"懒惰的"

@Lazy(懒加载):该注解用于惰性加载初始化标注的类、方法和参数。

在Spring中常用于单实例Bean对象的创建和使用;

单实例Bean懒加载:容器启动后不创建对象,而是在第一次获取Bean创建对象时,初始化。

在这里插入图片描述

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、项目结构

在这里插入图片描述

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、测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大树下躲雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值