@Lookup Annotation in Spring

In this post of Spring annotation, we will look at the @Lookup annotation in Spring. The @Lookup annotation is useful in the method level dependency injection.

 

1. Why @Lookup Annotation in Spring

To put it in simple words, lookup method injection is the process to override a Spring bean at the runtime. The constructor and property are the most common used dependency injection methods. Both the options happen during the initialization of the Bean. The @Lookup annotation in Spring is helpful when we like to implement a factory method which returns a new bean on every call without we implementing the method. Here are some of the most common use cases for the @Lookup:

  1. Injecting prototype scoped bean in singleton bean.

To use this annotation, we need to annotate the method with @Lookup. Let’s look at some example for a better understanding:

 

1.1 Injecting prototype scoped bean in singleton bean.

Let’s take an example where we want to refer prototype scoped bean in a singleton bean. The first challenge in this use case is getting access of the prototype bean in the singleton bean.This is how our prototype class look like:

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

    public String getNotification(){
        return  "Order Placed";
    }
}

Our singleton class with prototype bean

@Component
public class OrderService {

    public void sendOrderNotificationMsg(){

        PlaceOrderNotification notification = getPlaceOrderNotification();

        //This will create a new instance every time  we call notification method
    }

    public PlaceOrderNotification getPlaceOrderNotification(){

        // This implementation will be overridden by dynamically generated subclass
        return  null;
    }
}

In the OrderService class, the getPlaceOrderNotification() method returns null. Spring uses CGLIB library to dynamically override this method to provide implementations. This is how the Spring generated code look like:

public PlaceOrderNotification getPlaceOrderNotification(){
    return applicationContext.getBean(PlaceOrderNotification.class);
}

 

2. Limitations or Restrictions

While using the lookup annotation, there are certain conditions for Spring to generate the code dynamically:

  1. Bean class can not be final.
  2. Method with @Lookup annotation cannot be private, static or final.

[pullquote align=”normal”]The container will generate runtime subclasses of the method’s containing class via CGLIB, which is why such lookup methods can only work on beans that the container instantiates through regular constructors (i.e. lookup methods cannot get replaced on beans returned from factory methods where we can’t dynamically provide a subclass for them). [/pullquote]

 

Summary

In this post, we look at the @Lookup annotation in Spring. We learned how and when to use the lookup annotation in your Spring application.The source code for this post is available on the GitHub.