Pale Blue Dot
Pale Blue Dot

Reputation: 581

Prototype Bean Destruction

I have the below PROTOTYPE class .

1, Will my DemoService objects destroyed by spring?And will it be garbage collected? 2. How can i manually destroy the DemoService so it is Garbage Collected?

@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

@RestController
public class GreetingController {

@Autowired
private DemoService demoService;

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

Upvotes: 2

Views: 332

Answers (1)

Oleg
Oleg

Reputation: 6314

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.

You need to get a reference to it using the 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.

Many more ways to get and instance of a prototype bean see https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

Upvotes: 2

Related Questions