如何验证一个实例是单实例还是多实例

在学习spring框架时我遇到一个问题,那就是在默认情况下spring框架一直都是单例模式,但是光凭普通の代码和运行结果根本无法看出spring框架使用的单实例还是多实例,那到底该如何进行验证呢?接下来我们来看一段代码

以下代码来自于https://www.tutorialspoint.com/spring/spring_bean_scopes.htm 

实体类

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

 测试类

我们看这段代码,当我们第一次获取对象时对对象的变量进行了赋值,设置Message为I'm object A,然后我们获取第二个对象,我们没有对magess进行赋值,但是当我们打印以下代码时会打印出:

Your Message : I'm object A
Your Message : I'm object A

由此可以看出第二个对象和第一个对象用的是同一个实例 

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

XML配置

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "singleton">
   </bean>

</beans>

猜你喜欢

转载自blog.csdn.net/qq_40929531/article/details/87823282