欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring中的@Lazy注解用法實(shí)例

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

一、@Lazy注解

1、@Lazy注解作用

lazy 翻譯過(guò)來(lái)是"懶惰的"

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

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

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

在這里插入圖片描述

2、@Lazy

可標(biāo)注在類(lèi)、方法、構(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、項(xiàng)目結(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注冊(cè)配置類(lèi)

package com.dashu.config;
import com.dashu.bean.Persion;
import org.springframework.context.annotation.*;
/**
 * @Configuration 注解:告訴Spring這是一個(gè)配置類(lèi)
 *
 * 配置類(lèi) == 配置文件(beans.xml文件)
 *
 */
@Configuration
public class BeanConfig {
    @Lazy
    @Bean
    public Persion persion(){
        System.out.println("初始化Persion...");
        return new Persion("張三",20);
    }
}

4、測(cè)試類(lèi)

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時(shí),初始化。之后的獲取都是同一個(gè)對(duì)象
         */
        Persion persion1 = (Persion) annotationConfigApplicationContext.getBean("persion");
        Persion persion2 = annotationConfigApplicationContext.getBean(Persion.class);
        System.out.println(persion1 == persion2);
    }
}

5、測(cè)試結(jié)果

在這里插入圖片描述

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

相關(guān)文章

最新評(píng)論