简体   繁体   English

原型 Bean 销毁

[英]Prototype Bean Destruction

I have the below PROTOTYPE class .我有以下 PROTOTYPE 类。

1, Will my DemoService objects destroyed by spring?And will it be garbage collected? 1、我的DemoService对象会不会被spring销毁?会不会被垃圾回收? 2. How can i manually destroy the DemoService so it is Garbage Collected? 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
}

I am injecting DemoService prototype class in the singleton class GreetingController我在单例类 GreetingController 中注入 DemoService 原型类

@RestController
public class GreetingController {

@Autowired
private DemoService demoService;

    @GetMapping("/greeting")
    public String greeting()
    
    {
    
    demoService. //call to demoService
    
    return  "Hello ";
    }

If you use a prototype bean this way it's only going to be created once when the singleton bean is created and it will only be destroyed when the spring context is shutdown.如果您以这种方式使用原型 bean,它只会在创建单例 bean 时被创建一次,并且只会在 spring 上下文关闭时被销毁。

You need to get a reference to it using the ApplicationContext您需要使用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 ";
    }
}

Then it will be garbage collected when you stop using it as any other java object.然后,当您停止将其用作任何其他 Java 对象时,它将被垃圾收集。

Many more ways to get and instance of a prototype bean see https://www.baeldung.com/spring-inject-prototype-bean-into-singleton更多获取原型 bean 和实例的方法请参见https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM