Java 原型豆销毁
我有下面的原型课 1、我的Java 原型豆销毁,java,spring,spring-boot,spring-mvc,garbage-collection,Java,Spring,Spring Boot,Spring Mvc,Garbage Collection,我有下面的原型课 1、我的DemoService对象会被spring销毁吗?它会被垃圾收集吗? 2.如何手动销毁DemoService,使其被垃圾收集 @Service @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS) public class DemoService { @Autowired private DaoCall daoCall;
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
}
如果您以这种方式使用原型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对象使用时,它将被垃圾收集
获取原型bean实例的更多方法请参见,因此我有3个疑问1)我在示例中使用的方法是将原型bean注入Singleton bean的正确方法。还是您的方法?2) 由于我的DemoService prototype作用域,是否会出现内存泄漏。从您的回答来看,我猜不会有3)如果您以这种方式使用prototype bean,那么在创建singleton bean时,它只会创建一次。
。您为什么这么说?请您解释一下1)您的方式不正确。我在这里展示的方式以及您在链接页面中看到的其他方式都是正确的。2) 只有创建它,它的行为才会与任何其他java对象完全相同。3) Spring创建单例bean并将原型bean注入其中,这种情况只发生一次。
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 ";
}
}