博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
@Lazy注解学习
阅读量:3674 次
发布时间:2019-05-21

本文共 1099 字,大约阅读时间需要 3 分钟。

转自:

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

  • @Lazy注解是什么

  • @Lazy注解怎么使用

 

1,@Lazy注解是什么

 

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

 

 

 

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @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容器启动的加载时间

转载地址:http://bvhbn.baihongyu.com/

你可能感兴趣的文章
Lua中的元表元方法
查看>>
第九章 质量与变更管理
查看>>
Rabbitmq高级特性及集群
查看>>
RocketMq入门
查看>>
RocketMQ高级原理详解
查看>>
RocketMQ应用
查看>>
kafka搭建与使用
查看>>
docke学习内容之二
查看>>
SpringDataJpa学习一
查看>>
springboot中的日志框架
查看>>
springboot的MVC自动配置
查看>>
Springboot中对mvc进行扩展
查看>>
一文读懂HashMap
查看>>
ConcurrentModifcationException详解
查看>>
史上最全的PHP正则表达式
查看>>
理解Mysql prepare预处理语句
查看>>
预编译语句(Prepared Statements)介绍,以MySQL为例
查看>>
单利模式
查看>>
gdal学习笔记1-读取数据信息
查看>>
python关于print中数据传输的用法
查看>>