亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring中的@Lazy注解用法實例

 更新時間:2023年08月12日 08:51:48   作者:大樹下躲雨  
這篇文章主要介紹了Spring中的@Lazy注解用法實例,在Spring中常用于單實例Bean對象的創(chuàng)建和使用,單實例Bean懶加載容器啟動后不創(chuàng)建對象,而是在第一次獲取Bean創(chuàng)建對象時,初始化,需要的朋友可以參考下

一、@Lazy注解

1、@Lazy注解作用

lazy 翻譯過來是"懶惰的"

@Lazy(懶加載):該注解用于惰性加載初始化標(biāo)注的類、方法和參數(shù)。

在Spring中常用于單實例Bean對象的創(chuàng)建和使用;

單實例Bean懶加載:容器啟動后不創(chuàng)建對象,而是在第一次獲取Bean創(chuàng)建對象時,初始化。

在這里插入圖片描述

2、@Lazy

可標(biāo)注在類、方法、構(gòu)造方法、參數(shù)、字段上

@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、項目結(jié)構(gòu)

在這里插入圖片描述

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、測試結(jié)果

在這里插入圖片描述

到此這篇關(guān)于Spring中的@Lazy注解用法實例的文章就介紹到這了,更多相關(guān)Spring的@Lazy內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論