spring注解之@Lazy

今天主要从以下几方面来介绍一下@Lazy注解

  • @Lazy注解是什么

  • @Lazy注解怎么使用

1,@Lazy注解是什么

 

@Lazy注解用于标识bean是否需要延迟加载,源码如下:

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

只有一个参数,默认是true,也就是说只要加了这个注解就会延迟加载

2,@Lazy注解怎么使用

 

没加注解之前主要容器启动就会实例化bean,如下:

AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
创建user实例

而加上@Lazy注解则必须在第一次调用的时候才会加载如下:

/**
    * 定义一个bean对象
    * @return
    */
   @Scope
   @Lazy
   @Bean(value="user0",name="user0",initMethod="initUser",destroyMethod="destroyUser")
   public User getUser(){
       System.out.println("创建user实例");
       return new User("张三",26);
   }
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
User bean2 = applicationContext2.getBean(User.class);
创建user实例
实例1 === User [userName=张三, age=26]

@Lazy注解注解的作用主要是减少springIOC容器启动的加载时间