Spring Dependency Injection Tutorial with Code Example

What is dependency?

It is a technique where an object supplies the dependency of another object.

a) A dependency is an object that can be used as a service.

b) Injection is the passing of a dependency to  a dependent object (receiving class) that would use it.

How does Spring finds the dependency?

a) Spring creates the service that needs to be injected

b) Spring injects the service as a dependency to another class.

These things are handled by Spring Inversion of Control Container.

In other words, imagine this example

private Addition add = new Addition(); Here we create the instance using new Addition() and then assign it to add object so that add object can then be used later.

How do you tell Spring to create that service?

a) In order for spring to be able to “create the service“, an annotation called @Component needs to be added on that class which needs to be injected as a dependency. Component is basically a bean class.

b) In order for spring to be able to “inject the service” as a dependency, an annotation called @Autowired needs to be added above the service.

Who is creating Spring?

a) The way we create Spring is basically using the annotation @RunWith(SpringJUnit4ClassRunner.class) It instantiates the Spring framework and it needs an application context in order to instantiate.

b) Application context can be provided via the annotation @ContextConfiguration(locations={“/applicationContext.xml”})

How does Spring know where to search for a Component/Bean? Or What is there in the applicationContext.xml

a) Inside the application context xml file the aim is to specify the path where the spring should look for in order to find the components/bean that needs to be created as a service and then later injected.

b) The way the path is specified in the application context xml is using the format:

<context:component-scan base-package="----location to the package where the bean is present---"/>

This field component-scan tells the spring –  the location (package) where it should look for in order to find the component/bean. Spring then goes to that location and finds the component in order to create the service.

NOTE:

Refer to my github project in order to understand this tutorial: Spring Dependency Injection Example

 

Advertisements

One thought on “Spring Dependency Injection Tutorial with Code Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s