当前位置: 首页 > 知识库问答 >
问题:

如何在Spring只消灭一颗豆子?[副本]

宋典
2023-03-14
<?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="st" class="spring17.Student">
            <property name="sno" value="101"/>
            <property name="sname" value="Smith"/>
            <property name="age" value="20"/>
        </bean>

        <bean id="st1" class="spring17.Student">
            <property name="sno" value="102"/>
            <property name="sname" value="Scott"/>
            <property name="age" value="22"/>
        </bean>

</beans>
package spring17;

import org.springframework.context.support.GenericXmlApplicationContext;

public class SpringPrg {
    @SuppressWarnings("resource")
    public static void main(String args[])
    {
        GenericXmlApplicationContext gc=new GenericXmlApplicationContext("classpath:destroybean.xml");

        Student st=gc.getBean("st",Student.class);

        System.out.println(st);

        gc.destroy();
    }
}

当我调用gc.destroy()时,st1也会被销毁,这是我不希望的。您可能建议为st1添加lazy-init属性,但这不是我想要的。

提前谢了。

共有1个答案

潘刚洁
2023-03-14

但是,我想知道如何销毁具有特定ID的bean。

在我看来这是一个无效的问题。spring上下文被设计成一次初始化和销毁。您只销毁一个可能仍在被其他bean使用的有线bean的想法似乎确实很危险。据我所知,除了一些黑客行为之外,没有办法让spring忘记连接到集合中的一颗豆子。

如果您希望bean是动态的,那么我将使用某种StudentManagerbean来代替。此管理器将维护自己的student对象集合。这些学生不会通过Spring有线,但经理会。然后,您可以随意创建和销毁student对象,而不会产生可能的连接问题。

 类似资料:
  • 问题内容: 我已经在bean的“销毁方法”中放入了sysout语句。当我运行示例代码时,sysout没有得到输出。这是否意味着未调用销毁方法? 测试类别: 豆 配置文件: 问题答案: 您的示例无效,因为您没有关闭appcontext,只是让程序终止。 调用上下文,您将看到被调用的bean destroy-methods。

  • 我有两个包com.a.b.c和com.x.y.z。在com.a.b2.c中,我定义了这样一个组件: 在com.x.y.z中,我有一个类,我想像这样注入我的ClassA: 我需要做什么样的配置更改才能将我的类注入到我的其他类中?现在我得到了构建错误 org.springframework.beans.factory。NoSuchBeanDefinitionException:未找到依赖项的[com.

  • 我对Spring bean扫描有点困惑。 AFAIK我需要把

  • 我有一个从org.springframework.security.core.userdetails.user扩展而来的bean,并将这个bean与openid一起使用。bean看起来像: 控制器将Employee的实例接受为: @RequestMapping(值=“/addemp.do”,方法=RequestMethod.Post)public@ResponseBody String addEm

  • 我有一堆bean的Spring boot应用程序。他们的数量一天比一天增加。所以我总是需要模拟新的bean,否则测试就会失败。所以,问题很简单:如何强制Spring Boot测试只使用应用程序上下文中的几个特定bean而不是全部?

  • 我知道拳击是怎么做的。例如,当你写 Integer 时,正在调用 同样,我也可以看到拆箱的实现代码吗? 更新:在建议的问题中得到了回答。