• 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容器启动的加载时间

  • 相关阅读:
    String,StringBuffer和StringBuilder的异同
    博客迁移到reetsee.com
    一个好用的打印插件,功能强大
    html5中使用标签支持视频播放
    Extjs4 中在指定光标处插入值
    Javascript 创建对象方法的总结
    JS中的prototype
    在JS方法中返回多个值的三种方法
    JS ready和onload事件 比较分析
    JS中的“!!”
  • 原文地址:https://www.cnblogs.com/jtlgb/p/10096249.html
Copyright © 2020-2023  润新知