Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW