Spring高級之註解@lazy詳解(超詳細)

定義/作用

用於指定單例bean實例化的時機,在沒有指定此註解時,單例會在容器初始化時就被創建。而當使用此註解後,單例對象的創建時機會在該bean在被第一次使用時創建,並且只創建一次。第二次及以後獲取使用就不再創建。

在實際開發場景中,並不是所有bean都要一開始就被創建的,有些可以等到使用時才創建。此時就可以使用該註解實現。

此註解只對單例bean有用,原型bean時此註解不起作用。

源碼:

//可以作用在類上、方法上、構造器上、方法參數上、成員變量中。
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
	//是否延遲加載,默認是,如果設置爲false,那跟不使用該註解一樣。
    boolean value() default true;
}

@Lazy註解作用於類上時,通常與@Component及其衍生註解配合使用。
@Lazy註解作用於方法上時,通常與@Bean註解配合使用。

//與@component配合使用
@Component
@Lazy
public class UserService {

    
    public UserService(){
        System.out.println("userService創建了");
    }
}


@Configuration
@ComponentScan(basePackages = "lazyDemo")
public class SpringConfig {

    @Bean
    @Lazy
    //與@Bean註解配合使用
    public UserService userService1(){
        return new UserService();
    }
}

public class TestLazyDemo {

    private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

    @Test
    public void testLazyDemo() throws SQLException {


        System.out.println("容器初始化完成");
        UserService userService = (UserService) context.getBean("userService");
        UserService userService1 = (UserService) context.getBean("userService1");

    }
}


結果:
在這裏插入圖片描述
分析:
如果是立即加載的bean的話,下面那兩條語句應該先打印出來,如果是延遲加載的bean的話,會在第一次使用,getBean的時候創建。也可以打斷點測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章