Spring容器的懒加载

1、单例模式的对象什么时候被创建?是使用getBean()方法获取对象的时候创建呢?还是创建spring容器的时候创建?

我们可以测试一下:

先定义一个example类,为其定义一个无参数的构造方法:

public class ExampleBean {
   public ExampleBean() {
       System.out.println("创建了ExampleBean对象");
   }
   public void execute() {
       System.out.println("调用了execute方法");
   }
   public void init() {
       System.out.println("正在执行初始化方法中的操作。。。。");
   }
   public void destroy() {
       System.out.println("对象资源释放。。。");
   }
}

我们在applicationContext.xml文件中指定其为单例模式:

<!-- 创建一个ExampleBean对象 -->
    <bean id ="example" class="com.zlc.test.ExampleBean" init-method = "init"
     destroy-method="destroy" scope="singleton">
    </bean>

运行以下的代码:

public static void main(String[] args) {
        String conf = "applicationContext.xml";
        //创建容器对象
        AbstractApplicationContext ac = new ClassPathXmlApplicationContext(conf); 
               
    }

运行结果为:

由此我们可以看出,单例模式的对象,是在创建spring容器时就会马上创建的。但是非单例模式的对象并不会在此时马上创建

我们也可以设置单例模式的对象延迟加载,并不在创建spring容器时马上创建,而是在需要使用时再创建,也就是使用getBean()方法获取时再加载,设置延迟加载的方法是:

<bean lazy-init="true"></bean>

添加这个属性后的xml配置如下所示;

扫描二维码关注公众号,回复: 2508509 查看本文章
 <bean id ="example" class="com.zlc.test.ExampleBean" init-method = "init"
     destroy-method="destroy" scope="singleton" lazy-init="true">

加了这样的设置以后,就不会在创建spring容器时马上创建单例模式的对象了

猜你喜欢

转载自www.cnblogs.com/zlingchao/p/9403500.html