Spring bean destroy-method,singleton和prototype范围

Nik*_*war 20 java spring scope

我是Spring框架的新手,从一些教程开始学习它.

我有以下文件,

#MainProgram.java

package test.spring;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainProgram {
        public static void main(String[] args) {
              AbstractApplicationContext context = 
                              new ClassPathXmlApplicationContext("Bean.xml");     
              HelloSpring obj = (HelloSpring) context.getBean("helloSpring");
              obj.setMessage("My message");
              obj.getMessage();
              context.registerShutdownHook();

        }
 }
Run Code Online (Sandbox Code Playgroud)

#HelloSpring.java

package test.spring;

public class HelloSpring   {
     private String message;

     public void setMessage(String message){
      this.message  = message;
      System.out.println("Inside setMessage");
   }

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

   public void xmlInit() {
    System.out.println("xml configured  initialize");
   } 

    public void xmlDestroy() {
    System.out.println("xml configured destroy");
    }

  }
Run Code Online (Sandbox Code Playgroud)

#Bean.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="helloSpring" class="test.spring.HelloSpring" 
          scope="prototype" init-method="xmlInit" destroy-method="xmlDestroy">

     </bean>
     </beans>
Run Code Online (Sandbox Code Playgroud)

当我拿出scope="singleton" 我的输出时是:

 xml configured  initialize
 Inside setMessage
 Your Message : My message
 xml configured destroy
Run Code Online (Sandbox Code Playgroud)

当我拿出scope="prototype" 我的输出时是:

 xml configured  initialize
 Inside setMessage
 Your Message : My message
Run Code Online (Sandbox Code Playgroud)

xmlDestroy()使用singleton范围bean 调用方法,但不能prototype 帮助我以下,

它是否正确?如果是这样,可能的原因是什么?

我也有一些疑问,

什么是差异或关系 ApplicationContext , AbstractApplicationContext and ClassPathXmlApplicationContext

Man*_*ngh 39

xmlDestroy() 使用单例范围bean调用方法,但不使用原型调用

Spring不管理原型bean的完整生命周期:容器实例化,配置,装饰和组装原型对象,将其交给客户端,然后不再了解该原型实例.为了释放资源,尝试实现自定义bean后处理器.

与单个bean不同,弹簧容器管理整个生命周期

您可以查看此基本教程,了解不同上下文之间的差异

参考文档