Spring IoC and dependency injection

By convention, in Spring, objects that are managed by Spring container are usually called beans. They form the backbone of our application. In Java, there are two ways to manage an object's dependencies. The first way is that the object itself either instantiates its dependencies, for example, inside its constructor, by invoking the constructors of its dependencies or locates its dependencies by using a look-up pattern. The following is an example of RegistrationService, which sends an email to users after a successful registration. For simplicity, we will focus on the dependencies part and skip the details of registration and sending emails. 

The following code listing shows how RegistrationService instantiates MailSender in its constructor:

public class RegistrationService {
private MailSender mailSender;
public RegistrationService() {
// Instantiate dependencies itself
this.mailSender = new MailSender();
}
// ... other logics
}

As you can see, by instantiating MailSenderRegistrationService takes control of managing its dependencies. This is the first way of managing dependencies.

Let's take a look at the second way, which relies on a container, in our case, Spring, to inject its dependencies through its constructors or its setters. For example, we can change RegistrationService to the following:

public class RegistrationService {
private MailSender mailSender;
public RegistrationService(MailSender mailSender) {
this.mailSender = mailSender;
}
// ... other logics
}

As you can see, we add a MailSender instance as an argument of the constructor of RegistrationService. In this way, RegistrationService has no control over its dependency. Spring takes responsibility for instantiating the MailSender instance now. The control of the dependency is inverted. And that's where the name, Inversion of Control (IoC), comes from.

So, how does Spring know what dependencies a class needs? It uses the configuration metadata that we provide. In the configuration, we specify what objects need to be created and what their dependencies are. To set up a Spring container, the traditional way is to put the configuration metadata inside an XML file, usually named applicationContext.xml. Starting from Spring 2.5, we can use annotation-based configuration to spin up the container. And starting from Spring 3.0, we can use the Java-based configuration to define the configuration with zero XML configuration. Nowadays, the XML-based configuration is considered to be outdated and should be used in the legacy code. In our example, we will use the Java-based configuration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.131.255