Using @Lookup annotation with arguments

In this post under Spring Core, I will explain with example how to use “@Lookup” annotation with arguments.

In the previous post under Spring Core, I showed the purpose and how to use “@Lookup” annotation without any arguments.

Just for recap,
1) “@Lookup” annotation is applied on the method level
2) It tells Spring to create a bean of a type, which is used as return type of the annotated method.

So if we use the below code

@Lookup
public ContainedBean createContainedBean() {
        return null;
}

This tells the Spring to override the default implementation of method “createContainedBean” in such a way that it returns an instance of “ContainedBean” (i.e., return type) every time this method is called.

Now if I replace the above code snippet by providing an argument to “@Lookup” annotation as shown below

@Lookup("displayBean")
public ContainedBean createContainedBean() {
        return null;
}

This new change tells the Spring to override the default implementation of method “createContainedBean” in such a way that it returns an instance of bean named “displayBean” every time this method is called.

This is how “@Lookup” works when used with arguments.

Below is the classes used for our example for your reference

ContainedBean

package core.package43;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("displayBean")
@Scope("prototype")
public class ContainedBean {
    private static int instanceCount = 0;
    private int id;

    public ContainedBean() {
        id = instanceCount;
        instanceCount = instanceCount + 1;
    }

    public void display() {
        System.out.println("ContainedBean Instance Id: " + id);
    }
}

ContainerBean

package core.package43;

import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

@Component
public class ContainerBean {
    public void display() {
        ContainedBean containedBean = createContainedBean();
        containedBean.display();
    }

    @Lookup("displayBean")
    public ContainedBean createContainedBean() {
        return null;
    }
}

Main class

package core.package43;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan(basePackages = "core.package43")
public class Example43 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example43.class);
        ContainerBean containerBean = applicationContext.getBean("containerBean", ContainerBean.class);
        containerBean.display();
        containerBean.display();
        containerBean.display();
    }
}

Leave a comment