1. Overview
In this quick article, we’re going to learn about creating a prototype-scoped bean with runtime arguments in Spring.
In Spring, there are many different bean scopes, but the default scope is singleton, which means that singleton-scoped beans will always produce the same object.
Alternatively, we can use the prototype-scoped bean if we need a new instance from the container every time. However, in most cases, we encounter issues if we want to instantiate the prototype from a singleton bean or transfer the dynamic parameter to prototype beans.
Spring provides many methods to achieve these objectives, which we’ll discuss in-depth in this tutorial.
2. Create a Prototype Bean With Dynamic Arguments
We sometimes need to initialize a Spring bean with dynamic arguments as input in each initialization. Prototype beans can be assigned different dynamic parameters through Spring using a variety of methods.
We’ll go through them one by one and see their pros and cons.
First, let’s first create a prototype bean Employee:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
Also, let’s create a config for our Employee prototype bean:
@Configuration
public class EmployeeConfig {
@Bean(name = "Employee")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Employee createPrototype(String name) {
return new Employee(name);
}
}
2.1. Using Application Context
Generally, this is the most basic and simple way of getting a prototype bean using the ApplicationContext.
Let’s inject the ApplicationContext into our component:
@Component
public class UseEmployeePrototype {
private ApplicationContext applicationContext;
@Autowired
public UseEmployeePrototype(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void usePrototype() {
Employee employee = (Employee) applicationContext.getBean("Employee", "sachin");
employee.printName();
}
}
As we see here, we’re tightly coupling the bean creation to the ApplicationContext. Thus, the approach may be impacted if we change our bean implementation.
2.2. Using the Factory Method
Spring provides the ObjectFactory<T> interface to produce on-demand objects of the given type.
Let’s create an EmployeeFactory for our Employee bean using ObjectFactory:
public class EmployeeBeanUsingObjectFactory {
@Autowired
private ObjectFactory employeeObjectFactory;
public Employee getEmployee() {
return employeeObjectFactory.getObject();
}
}
Here, with every call to getEmployee(), Spring will return a new Employee object.
2.3. Using @Lookup
Alternatively, method injection using the @Lookup annotation can solve the problem. Any method that we inject with a @Lookup annotation will be overridden by the Spring container, which will then return the named bean for that method.
Let’s create a component and create a method with the @Lookup annotation to get the Employee object:
@Component
public class EmployeeBeanUsingLookUp {
@Lookup
public Employee getEmployee(String arg) {
return null;
}
}
A method annotated with @Lookup, such as getEmployee(), will be overridden by Spring. As a result, the bean is registered in the application context. A new Employee instance is returned each time we call the getEmployee() method.
Spring will use CGLIB to generate the bytecode, and neither the class nor the method can be final.
Now, let’s test the @Lookup method for a given prototype bean and check that it returns different instances:
@Test
public void givenPrototypeBean_WhenLookup_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingLookUp firstContext = context.getBean(EmployeeBeanUsingLookUp.class);
EmployeeBeanUsingLookUp secondContext = context.getBean(EmployeeBeanUsingLookUp.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
2.4. Using Function
Spring provides another option, Function, for creating prototype beans at run time. We can also apply the arguments to newly created prototype bean instances.
First, let’s create a component using Function where the name field will be added to the instance:
@Component
public class EmployeeBeanUsingFunction {
@Autowired
private Function<String, Employee> beanFactory;
public Employee getEmployee(String name) {
Employee employee = beanFactory.apply(name);
return employee;
}
}
Further, now, let’s add a new beanFactory() in our bean configuration:
@Configuration
public class EmployeeConfig {
@Bean
@Scope(value = "prototype")
public Employee getEmployee(String name) {
return new Employee(name);
}
@Bean
public Function<String, Employee> beanFactory() {
return name -> getEmployee(name);
}
}
Lastly, we’ll check if the instances are different:
@Test
public void givenPrototypeBean_WhenFunction_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingFunction firstContext = context.getBean(EmployeeBeanUsingFunction.class);
EmployeeBeanUsingFunction secondContext = context.getBean(EmployeeBeanUsingFunction.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
2.5. Using ObjectProvider
Spring provides ObjectProvider<T>, which is an extension of the existing ObjectFactory interface.
Let’s inject the ObjectProvider and get the Employee object using ObjectProvider:
public class EmployeeBeanUsingObjectProvider {
@Autowired
private org.springframework.beans.factory.ObjectProvider objectProvider;
public Employee getEmployee(String name) {
Employee employee = objectProvider.getObject(name);
return employee;
}
}
Now, let’s test and check if the instances are different:
@Test
public void givenPrototypeBean_WhenObjectProvider_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingObjectProvider firstContext = context.getBean(EmployeeBeanUsingObjectProvider.class);
EmployeeBeanUsingObjectProvider secondContext = context.getBean(EmployeeBeanUsingObjectProvider.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
3. Conclusion
In this short tutorial, we learned several ways of creating prototype-scoped beans dynamically in Spring.
As always, the complete code for this tutorial is over on GitHub.