0 votes
2k views
in Spring by
lookup-method in spring example or spring lookup-method injection

1 Answer

0 votes
by (2.8k points)
Generally, we use two scopes in spring: singletons and prototypes
 
Singletons scope implements the Singleton pattern, meaning there is only one single instance at the runtime (in a JVM). Spring instantiates it during context creation, caches them in the context, and serves them from the cache when needed. 
 
Prototypes scope are instantiated each time you access the context to get the bean. Means it always give new bean object.
 
Problems occured when you need to inject a prototype-scoped bean in a singleton-scoped bean. Since singletons are created (injected) during context creation. It is only time when Spring context is accessed and thus prototype-scoped beans are injected only once, thus defeating their purpose. 
 
In order to inejct prototypes into singletons, and side-by-syde with setter and constructor injection, Spring proposes another way for injection, called method injection. See the following way: since singletons are instantiated at context creation, it changes the way prototype-scoped are handled, from injection to created by an abstract method. 
 
There are following code snippet to achieve method injection:
 
package com.bean.scope.lookup;
 
public class Address {
 
public String fullAddress(){
return "New Delhi - 85";
}
}
 
package com.bean.scope.lookup;
 
public abstract class Employee {
 
public abstract Address getAddress();
 
public void getMyAddress(){
System.out.println("Object: " + getAddress() + " FullAddress" + getAddress().fullAddress());
}
}
 
xsi:schemaLocation="
 
<bean id="employee" class="com.bean.scope.lookup.Employee" scope="singleton">
     <lookup-method name="getAddress" bean="address"/> 
</bean>
 
<bean id="address" class="com.bean.scope.lookup.Address" scope="prototype" />
 
</beans> 
 
package com.bean.scope.lookup;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestMain {
 
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/resources/context.xml");
Employee employee = (Employee) context.getBean("employee");
System.out.println(employee);
employee.getMyAddress();
 
Employee employee1 = (Employee) context.getBean("employee");
System.out.println(employee1);
employee1.getMyAddress();
}
 
}
 
OutPut
Object: [email protected] FullAddressNew Delhi - 85
Object: [email protected] FullAddressNew Delhi - 85

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...