Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在调用“后,我如何访问bean?”;“关闭”;方法「;ClassPathXmlApplicationContext";?_Java_Spring_Spring Boot - Fatal编程技术网

Java 在调用“后,我如何访问bean?”;“关闭”;方法「;ClassPathXmlApplicationContext";?

Java 在调用“后,我如何访问bean?”;“关闭”;方法「;ClassPathXmlApplicationContext";?,java,spring,spring-boot,Java,Spring,Spring Boot,在调用context变量(类型为ClassPathXmlApplicationContext)上的close方法后,spring调用destoy方法(在我的例子中是doMyCleanupStuff) 这不意味着特定的bean被破坏了吗 这不意味着它将从应用程序上下文中删除吗?如果是,spring中是否存在此对象的多个引用 应用程序上下文(XML)文件: 您已经有了一个引用,即使在关闭上下文后,该引用仍将保留。但是,使用存储库或其他已关闭的资源(如数据源、connectionfactory等)进行

在调用
context
变量(类型为ClassPathXmlApplicationContext)上的close方法后,spring调用destoy方法(在我的例子中是doMyCleanupStuff)

这不意味着特定的bean被破坏了吗

这不意味着它将从应用程序上下文中删除吗?如果是,spring中是否存在此对象的多个引用

应用程序上下文(XML)文件:


您已经有了一个引用,即使在关闭上下文后,该引用仍将保留。但是,使用存储库或其他已关闭的资源(如数据源、connectionfactory等)进行操作会产生错误。它还可能导致未正确清理东西(如果您将其保持在静态的某个位置),然后内存泄漏。
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Define your beans here -->
    <bean id="myFortuneService"
        class="com.luv2code.springdemo.HappyFortuneService">
    </bean>
    
    <bean id="myCoach"
        class="com.luv2code.springdemo.TrackCoach"
        init-method="doMyStartupStuff"
        destroy-method="doMyCleanupStuffYoYo">
        <constructor-arg ref="myFortuneService" />
    </bean>
    
</beans>

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifeCycleDemoApp {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beanLifeCycle-applicationContext.xml");
        
        Coach theCoach = context.getBean("myCoach", Coach.class);
        System.out.println("Mem location for theCoach: " + theCoach);

        context.close();
        
        System.out.println("Mem location for theCoach: " + theCoach);
    }

}