gpt4 book ai didi

java - 在 spring 中访问缓存的 ApplicationContext

转载 作者:行者123 更新时间:2023-11-30 03:51:40 24 4
gpt4 key购买 nike

我需要在 2 个不同的类中两次从同一个 ApplicationContext 获取一个单例 bean。

示例片段:

CLass A {
public void foo(){
ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
// do more stuff..
}
CLass B {
public void bar(){
ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
// do more stuff..
}

由于 MyParametrizedSingletonClass 是单例,因此如果针对相同的构造函数参数多次调用其构造函数,则会抛出错误。

如何使用 spring 缓存和重用 ApplicationContext?

最佳答案

您正在创建两个不同的上下文,因此即使 bean 是单例的,它也会为每个上下文创建单个实例,

如果你想缓存应用程序上下文 you can create a class and provide singleton instance of application context

关于java - 在 spring 中访问缓存的 ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com