DEV Community

Arjun Shetty
Arjun Shetty

Posted on

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

Top comments (0)