Spring — Lookup Method Dependency Injection | Code Factory

Spring Tutorial Index Page: Link

Create Java Project

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans> <!-- for Car interface lookup method -->
<bean id="c" class="com.codeFactory.beans.Car">
<lookup-method name="myCarEngine" bean="e1" />
</bean>

<bean id="e1" class="com.codeFactory.beans.Engine">
<property name="name" value="JLR Engine"></property>
</bean>

<!-- for Bus abstract lookup method -->
<bean id="b" class="com.codeFactory.beans.Bus">
<lookup-method name="myBusEngine" bean="e2" />
</bean>

<bean id="e2" class="com.codeFactory.beans.Engine">
<property name="name" value="TATA Engine"></property>
</bean>

<!-- for Truk concrete lookup method -->
<bean id="t" class="com.codeFactory.beans.Truk">
<lookup-method name="myTrukEngine" bean="e3" />
</bean>

<bean id="e3" class="com.codeFactory.beans.Engine">
<property name="name" value="BharatBenz Engine"></property>
</bean>
</beans>
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public abstract class Bus {
abstract public Engine myBusEngine();
}
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public interface Car {
public Engine myCarEngine();
}
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class Engine {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class Truk {
public Engine myTrukEngine() {
Engine e = new Engine();
e.setName("Eicher");
return e;
}
}
package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Bus;
import com.codeFactory.beans.Car;
import com.codeFactory.beans.Truk;
/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

Car c = (Car) context.getBean("c");
System.out.println(c.myCarEngine().getName());
System.out.println(c.getClass().getCanonicalName());

Bus b = (Bus) context.getBean("b");
System.out.println(b.myBusEngine().getName());
System.out.println(b.getClass().getCanonicalName());

Truk t = (Truk) context.getBean("t");
System.out.println(t.myTrukEngine().getName());
System.out.println(t.getClass().getCanonicalName());
}
}
JLR Engine
com.codeFactory.beans.Car$$EnhancerByCGLIB$$a3f74ae8
TATA Engine
com.codeFactory.beans.Bus$$EnhancerByCGLIB$$e4ceb238
BharatBenz Engine
com.codeFactory.beans.Truk$$EnhancerByCGLIB$$cc6df530

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store