Spring 中的单例 bean 默认是马上初始化的,但是可以设置为延迟初始化。类似于单例模式中的懒加载和即时加载。
通过 XML 配置文件,或者注解都可以配置懒加载。
示例1:即时初始化
TestBean 类内容:
package demo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
//@Lazy(value = true)
public class TestBean implements InitializingBean, ApplicationContextAware {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("setApplicationContext");
}
}
Main 类内容:
package demo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class);
System.out.println("finish");
}
}
执行 Main 类,会输出:
setApplicationContext
afterPropertiesSet
finish
示例2:延迟初始化
给 TestBean 类加上注解@Lazy(value = true)
,再次执行 Main 类,会输出:
finish
可以看到,TestBean 没有被初始化。
如果注解是@Lazy(value = false)
,那么还是即时初始化。
示例3:初始化被设置为延迟初始化的bean
延迟初始化的bean,什么时候会触发初始化?被用到的时候,例如被注入到另一个即时单例bean中。
例如,我们新建一个 Main2 类,内容如下:
package demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan
@Component
public class Main2 {
@Autowired
private TestBean testBean;
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Main2.class);
System.out.println("finish");
}
}
执行该类,结果是:
setApplicationContext
afterPropertiesSet
finish