I am trying to understand different Bean Scopes. When working with @RequestScope I don’t see message printed to console from constructor and destroy() method in order to confirm when this Bean is really being created or destroyed. This works for @Singleton and @Prototype Beans.
Person.java
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class Person {
//PROPERTIES
public String name;
//CONSTRUCTOR
Person() {
System.out.println("Person Created");
}
//DESTROY
@PreDestroy
public void destroy() {
System.out.println("Person Destroyed");
}
}
Controller.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
//PROPERTIES
@Autowired Person person1; //New Instance/Bean
@Autowired Person person2; //New Instance/Bean
//=========================================================================================================
// SET PERSON NAME
//=========================================================================================================
@RequestMapping("setPersonName")
void setPerson() {
person1.name = "John";
person2.name = "Bill";
}
//=========================================================================================================
// GET PERSON NAME
//=========================================================================================================
@RequestMapping("getPersonName")
String getPerson() {
return person1.name + " - " + person2.name;
}
}