In my previous post under Spring Core, I have explained the use of “@Lookup” annotation and how to use it with or without its arguments.
In this post, I will show with example, how we can use “@Lookup” (with or without its argument) with a method that takes a local variable and instance variable as an arguments.
For our example, I use the class “ContainedBean” whose class structure is as shown below
ContainedBean
package core.package51;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class ContainedBean {
public void display(String name, String template) {
String message = String.format(template, name);
System.out.println(message);
}
}
In the above class structure, we have “display” method which takes two arguments “name” and “template”. The value of variable “name” will come from main class, the value of variable “template” will
come from “ContainerBean” whose class structure is as shown below
ContainerBean
package core.package51;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component
public class ContainerBean {
private String template = "Welcome %s";
public void display(String name) {
ContainedBean containedBean = createContainedBean();
containedBean.display(name, this.template);
}
@Lookup
public ContainedBean createContainedBean() {
return null;
}
}
As you can see in the above class structure, “ContainerBean” also has “display” method similar to “ContainedBean” but takes only one parameter “name”, which is given in the main method.
The “ContainerBean” calls “display” method of “ContainedBean” passing its instance variable “template” and its local parameter “name”.
The “createContainedBean” method is annotated with “@Lookup” annotation.
So when we call “display” method of “ContainedBean” bean (refer to line 12), the “createContainedBean” method creates an instance of “ContainedBean” class and calls its “display” method passing “name”
and “template” variable value as arguments.
Below is the main class, which shows how “ContainerBean” is initialized and used.
Main class
package core.package51;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "core.package51")
public class Example51 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example51.class);
ContainerBean containerBean = applicationContext.getBean(ContainerBean.class);
containerBean.display("John Doe");
}
}
Below is the output
Output
Welcome John Doe
In this way we can use “@Lookup” annotation with a method that takes a local variable and instance variable as an arguments