DEV Community

Arjun Shetty
Arjun Shetty

Posted on

1

Getting new instance every time in Java Spring Boot

This is one of the ways to get a new instance of a type everytime we request for it from a singleton scoped instance.

@Lookup Informs spring container to getBean from method decorated with this annotation.

Creating a method in configuration class so that it can be used anywhere configuration is injected.

//ApplicationConfiguration.java
@Lookup
public UserDTO getUserDTOProtoTypeBean() {
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Make sure the UserDTO class is decorated with @Scope("prototype"). Now in your consuming class call this method when you need a new instance.

@Component
public class UserMapper {

    @Autowired
    ApplicationConfiguration appConfig;

    public UserDTO ToDto(User userEntity) {
        var UserDTO = appConfig.getUserDTOProtoTypeBean();
        ...
    }
}
Enter fullscreen mode Exit fullscreen mode

Code On!

Originally Posted on Bitsmonkey

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs