Bootstrap your Spring Application – Bean Collaboration

Introduction

This is a series and it would make a lot of sense if read in a sequence. You can find all the posts under the heading “Spring Beginners to Professionals“. Now we know about the beans and the containers . We defined couple of beans as well. But what is an application good for if the beans do not interact? This post describes how to bootstrap your spring application.

Almost all applications will need beans to collaborate with each other and deliver some results. And this is achieved using Dependency Injection. Recalling our discussion from the Inversion of Control post, if a container supplies an instance of dependent bean into another bean then it is called dependency injection.

Dependency Injection

Remember our discussion about the OrderClient and the DataStore instances. Here are the required classes.

Now let us provide the Spring configuration either using XML

or annotations

Bootstrap your Spring Application

If you try to bootstrap this application using XML application context

or the annotation application context

The application would not be able to fetch the datastore object which is needed by the OrderClient object. It will show a message that data store is null.

Why so, didn’t Spring promise dependency injection by the container?

Yes! this doesn’t seem to be right! As we were claiming that spring will manage the dependencies itself and will return the appropriate bean. That means! we are probably missing something.

Here is what we are missing!

We never informed Spring about the collaborating beans. We need to explicitly tell Spring that OrderClient requires an instance of the DataStore and that’s logical. This is logical because if in case we have two implementations of the DataStore, how will Spring know which one to inject.

So let us inform Spring that we need the csvDataStore bean for the orderClient object. When Spring will have this information, it will deliver on its promises to manage the dependencies and inject them appropriately.

You can pick up any variant of the code and just build a small java project and run it. Of course you will need some jars, which you can download from Spring’s repository. If you are using Maven or Gradle, it makes things easier. Below is a pom file for maven project. The gradle would be on similar lines.

POM file for Maven

Oh! you can leave the log related dependency for now and just work with the spring dependencies.

Summary

Let me know in comments if you were able to run this mini application.

In Spring Dependency Injection exists in two major variant. Constructor based Dependency Injection and Setter based Dependency Injection. In the next post, we will discuss about Constructor based dependency injection and the troubles you may get into when using it.

Stay connected and keep learning.