ITPub博客

首页 > IT职业 > IT生活 > 一分钟学会spring注解之@Lazy注解

一分钟学会spring注解之@Lazy注解

IT生活 作者:snoopyzjs 时间:2021-09-09 10:00:14 0 删除 编辑

今天主要从以下几方面来介绍一下@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]


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1414/viewspace-2814961/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    104
  • 访问量
    1015