Posts

Showing posts with the label springboot

Spring Bean Life Cycle

 In Spring, the life cycle of a bean refers to the various stages that a bean goes through from its instantiation to its destruction. Spring provides several callback methods and interfaces that allows to interact with the bean during these stages. The typical life cycle of a Spring bean includes the following steps: 1. Instantiation : The bean is created by the Spring container through its defined instantiation mechanism. This can be done using either constructor injection or setter injection. 2. Populate Properties : After the bean is instantiated, Spring injects any necessary dependencies (properties or constructor arguments) into the bean. 3. BeanNameAware : If the bean implements the `BeanNameAware` interface, the Spring container sets the bean's name through the `setBeanName()` method. 4. BeanFactoryAware or ApplicationContextAware : If the bean implements the `BeanFactoryAware` or `ApplicationContextAware` interface, the Spring container sets the reference to the bean factor...

Protoype bean scope - real world usage

  Protoype scope illustration using Token Generator import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @SpringBootApplication public class PrototypeScopeExample {   public static void main(String[] args) {     SpringApplication.run(PrototypeScopeExample.class, args);   } } @Component @Scope("prototype") class PrototypeBean {   private String message;   public String getMessage() {     return message;   }   public void setMessage(String message) {     this.message = message;   } } @Component class ClientBean {   @Autowired   private PrototypeBean prototypeBean;   public void printMessage() {     prototypeBean.setMessage("Hello, World!");     System.out.pr...