最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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(懶加載):該注解用于惰性加載初始化標注的類、方法和參數(shù)。

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

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

在這里插入圖片描述

2、@Lazy

可標注在類、方法、構(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)文章

最新評論

瓦房店市| 公安县| 宝兴县| 巴里| 玉林市| 玛曲县| 仙游县| 渝北区| 兰考县| 波密县| 阳江市| 关岭| 农安县| 廊坊市| 华阴市| 兴仁县| 新蔡县| 徐闻县| 黄冈市| 嘉禾县| 威远县| 宁都县| 屏东市| 广河县| 炉霍县| 临泉县| 西和县| 金川县| 左云县| 安西县| 永泰县| 都江堰市| 封开县| 藁城市| 日照市| 江西省| 阳高县| 屏南县| 大理市| 武强县| 资溪县|