09 Lazy注解

文章目录

1 介绍

@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;

}

可用在类,方法,构造上

用于指定单例bean对象的创建时机,单例bean的生命周期默认与容器的生命周期相同,容器创建的时候创建bean,销毁的时候销毁bean。但是当使用了该注解之后,单例对象的创建时机就变成了第一次使用的时候创建。

这个注解只对单例bean有作用,多例bean在每次使用的时候都会创建该bean

2 演示

创建两个组件,一个使用该注解,一个不使用

package study.wyy.spring.anno.lazy.service;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @author by wyaoyao
 * @Description
 * @Date 2020/11/22 11:47 上午
 */
@Component
@Lazy(value = true)
public class AddressService {
    public AddressService() {
        System.out.println("AddressService 创建。。。。。");
    }

    public void saveAddress(){
        System.out.println("保存地址....");
    }
}

package study.wyy.spring.anno.lazy.service;

import org.springframework.stereotype.Component;

/**
 * @author by wyaoyao
 * @Description
 * @Date 2020/11/22 11:46 上午
 */
@Component
public class UserService {

    public UserService() {
        System.out.println("UserService 创建。。。。。");
    }

    public void saveUser(){
        System.out.println("保存用户....");
    }
}

配置类

package study.wyy.spring.anno.lazy.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author by wyaoyao
 * @Description
 * @Date 2020/11/22 11:53 上午
 */
@Configuration
@ComponentScan("study.wyy.spring.anno.lazy.service")
public class SpringConfig {
}

测试

package study.wyy.spring.anno.lazy.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import study.wyy.spring.anno.lazy.config.SpringConfig;
import study.wyy.spring.anno.lazy.service.AddressService;
import study.wyy.spring.anno.lazy.service.UserService;

/**
 * @author by wyaoyao
 * @Description
 * @Date 2020/11/22 11:53 上午
 */
public class Test {
    @org.junit.Test
    public void test01(){
        AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(SpringConfig.class);
        context.start();
        System.out.println("开始使用bean");
        UserService userService= context.getBean(UserService.class);
        AddressService addressService = context.getBean(AddressService.class);
    }
}

输出

UserService 创建。。。。。
开始使用bean
AddressService 创建。。。。。

UserService在容器创建的时候就创建了,但是AddressService在使用的时候才开始创建

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值