View RSS Feed

Spring Framework

Contextualized Dependency Lookup in Spring

Rate this Entry
by , 11-16-2011 at 12:16 PM (2646 Views)
At its core, Inversion of Control (IoC), and therefore Dependency Injection (DI) offers a mechanism for provisioning component dependencies and managing these dependencies throughout their lifecycles. A component that requires certain dependencies is often referred to as the dependent object or, in the case of IoC, the target. Generally, IoC can be broken down into two subtypes: Dependency Injection and Dependency Lookup. With Dependency Lookup IoC, a component must obtain a reference to a dependency. This differs from Dependency Injection where dependencies are injected into the component of the IoC container. The are two types of Dependency Lookup. In this tip, we will focus on Contextualized Dependency Lookup (CDL). CDL is similar, in some respects, to Dependency Pull, but in CDL, lookup is performed against the container that is managing the resource, not from a central registry, and it is usually performed at some set point. CDL works by having the component implement an interface similar to the one shown below:

Java Code:
import org.springframework.beans.factory.BeanFactory;

public interface ManagedComponent {
	public void performLookup(BeanFactory container);
}
The component implements this interface is then implemented and thus indicates to the container that it wishes to obtain a dependency. When the container is ready to pass dependencies to a component, it calls performLookup() on each component. The component can then look up its dependencies using the BeanFactory interface.

Java Code:
import org.springframework.beans.factory.BeanFactory;
import com.acme.springexamples.service.CarService;

public class ContextualizedDependencyLookup implements ManagedComponent {
	private CarService service;

	@Override
	public void performLookup(BeanFactory container) {
		this.service = (CarService) container.getBean("car_service");
	}
}

Submit "Contextualized Dependency Lookup in Spring" to Facebook Submit "Contextualized Dependency Lookup in Spring" to Digg Submit "Contextualized Dependency Lookup in Spring" to del.icio.us Submit "Contextualized Dependency Lookup in Spring" to StumbleUpon Submit "Contextualized Dependency Lookup in Spring" to Google

Comments