Friday, 13 September 2019

Spring boot: Create Prototype scoped bean with annotation


Spring beans are singleton by default. You can confirm the same using my previous post.

If you want to make a bean as prototype bean, you can use @Scope annotation.

Example

@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Employee newEmployee() {
 System.out.println("New bean is getting initialized");
 Employee emp = new Employee();
 emp.setId(1);
 emp.setFirstName("Krishna");
 emp.setLastName("Majety");
 return emp;
}

Find the below working application.

Employee.java
package com.sample.app.model;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;

 public Employee() {
  System.out.println("Constructor Called");
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public void print() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  System.out.println(builder.toString());

 }

}


EmployeeConfiguration.java
package com.sample.app.configuration;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.sample.app.model.Employee;

@Configuration
public class EmployeeConfiguration {

 @Bean
 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
 public Employee newEmployee() {
  System.out.println("New bean is getting initialized");
  Employee emp = new Employee();
  emp.setId(1);
  emp.setFirstName("Krishna");
  emp.setLastName("Majety");
  return emp;
 }
}

application.properties
logging.level.root=WARN


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import com.sample.app.configuration.EmployeeConfiguration;
import com.sample.app.model.Employee;

@SpringBootApplication
public class App {
 public static void main(String args[]) {
  System.out.println("Main Application running.......");
  ApplicationContext applicationContext = SpringApplication.run(App.class, args);

  System.out.println("ApplicationContext initialized");

  Employee emp1 = applicationContext.getBean(Employee.class);
  Employee emp2 = applicationContext.getBean(Employee.class);

  EmployeeConfiguration configuration = applicationContext.getBean(EmployeeConfiguration.class);
  Employee emp3 = configuration.newEmployee();
  Employee emp4 = configuration.newEmployee();

  System.out.println("emp1 = " + emp1);
  System.out.println("emp2 = " + emp2);
  System.out.println("emp3 = " + emp3);
  System.out.println("emp4 = " + emp4);
 }
}


Total project structure looks like below.

Run App.java.


You can see below messages in console.
Main Application running.......

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

ApplicationContext initialized
New bean is getting initialized
Constructor Called
New bean is getting initialized
Constructor Called
New bean is getting initialized
Constructor Called
New bean is getting initialized
Constructor Called
emp1 = com.sample.app.model.Employee@135606db
emp2 = com.sample.app.model.Employee@518caac3
emp3 = com.sample.app.model.Employee@68034211
emp4 = com.sample.app.model.Employee@4f74980d

From the output, you can confirm that, whenever I requests for a new bean, spring gives me new object.

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment