Using the @Lookup Annotation in Spring

tiuwill

Willian Ferreira Moya

Posted on July 5, 2024

Using the @Lookup Annotation in Spring

The @Lookup annotation is an injection (like @Inject, @Resource, @Autowired) annotation used at the method level. This annotation tells Spring to overwrite the method, redirecting to the bean factory to return a bean matching the return type of the method. This can be useful for some bean scopes, such as the prototype scope, which will return a new instance of the bean each time it is requested. By combining it with the @Lookup annotation, you can make things more dynamic.

Use Cases for @Lookup

Imagine that you have a bean that handles user-specific session data. Each request should have its own instance to avoid data conflicts.

Code example:

Let's say you have a prototype bean that gets the exact moment a user of your system has made a request.

@Component
@Scope("prototype")
public class UserSessionBean {

    private String userData;

    public UserSessionBean() {
        this.userData = "Session data for " + System.currentTimeMillis();
    }

    public String getUserData() {
        return userData;
    }

}

Enter fullscreen mode Exit fullscreen mode

Now you want Spring to get you a new bean to process a request and use this new bean's information to do some processing. In this example, it will look like a session object that can hold user information during the request context.

@Component
public class UserService {

    @Lookup
    public UserSessionBean getUserSessionBean() {
        // Spring will override this method to return a new instance of UserSessionBean
        return null;
    }

    public String processUserSession() {
        UserSessionBean userSessionBean = getUserSessionBean();
        return "Processing user session with data: " + userSessionBean.getUserData();
    }
}

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/session")
    public String getUserSession() {
        return userService.processUserSession();
    }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

By using the @Lookup annotation, you can make things more dynamic. In this example, it allows you to handle user-specific sessions, but you can be creative and create many more scenarios using this annotation.

If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!

Follow me!

💖 💪 🙅 🚩
tiuwill
Willian Ferreira Moya

Posted on July 5, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related