gpt4 book ai didi

java - 原型(prototype) Bean 销毁

转载 作者:行者123 更新时间:2023-12-04 08:54:45 24 4
gpt4 key购买 nike

我有以下 PROTOTYPE 类。
1、请问我的DemoService Spring 破坏的物体?它会被垃圾收集吗?
2. 如何手动销毁DemoService所以它是垃圾收集?

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class DemoService {


@Autowired
private DaoCall daoCall; //call to database.Connection will be closed by the connection pool.

@Autowired
private KafkaTemplate<String, String> template; //used to send message to Kafka
}
我在单例类 GreetingController 中注入(inject) DemoService 原型(prototype)类
@RestController
public class GreetingController {

@Autowired
private DemoService demoService;

@GetMapping("/greeting")
public String greeting()

{

demoService. //call to demoService

return "Hello ";
}

最佳答案

如果您以这种方式使用原型(prototype) bean,它只会在创建单例 bean 时创建一次,并且只会在 spring 上下文关闭时被销毁。
您需要使用 ApplicationContext 获取对它的引用

public class GreetingController implements ApplicationContextAware {
private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}

@GetMapping("/greeting")
public String greeting()

{

DemoService demoService = applicationContext.getBean(DemoService.class);
demoService. //call to demoService

return "Hello ";
}
}
然后,当您停止将其用作任何其他 java 对象时,它将被垃圾收集。
更多获取原型(prototype) bean 和实例的方法参见 https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

关于java - 原型(prototype) Bean 销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63892729/

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