SpringIOC容器一般是在启动的时候就实例化所有的单例Bean,如果需要延迟加载或者叫做延迟实例的话, 那就可以使用@Lazy注解。
Lazy 注解源码如下
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
boolean value() default true;
}
Lazy注解内就只有一个boolean类型的value属性,默认为true。(true代表延迟加载,false不做延迟加载)
在这里看@Lazy(value=false)是没有意义的(对象初始化的时候就创建)。
所以在需要使用的时候写上@Lazy就行了。