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...