Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between dependency injection and dependency look up?

Tags:

spring

What is Dependency look up?Could someone please clarify these two concepts.

like image 307
Balasubramani Avatar asked Jan 20 '15 06:01

Balasubramani


1 Answers

Dependency lookup is when the object itself is trying to find a dependency, such as:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
MyBean bean = applicationContext.getBean("myBean")

Here, the class itself is initializing the ApplicationContext through an XML, and it is searching in the context for the bean called myBean in the ApplicationContext

The Dependency injection is when a property is automatically bound when an instance is initialized. For example:

in the application-context.xml, we have one line which initialize the bean and another to initialize the object of, let's say, MyClass:

<bean id="myBean" class="org.mypackage.MyBean"/>
<bean id="myClass" class="org.mypackage.MyClass"/>

Then in MyClass, you have something like:

@Component
public class MyClass{

  @Autowired
  MyBean myBean;

  // ...
}    

In this case, you have specified that two instances of two beans are initialized. And the myClass bean has a property called myBean which is already initialized due to the injection

like image 196
Michael Avatar answered Oct 20 '22 14:10

Michael