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在使用的时候才开始创建