DI – Dependency injection by name and type

@Resource by default the name of the bean will be its class name in camelCase. That means, the SmsService instance, which will be put in the application context as a result of being annotated with @Component, will be named as smsService. To change the default name, we can supply a value element to @Component:

@Component(value = "sms")
public class SmsService implements MessageService {

    @Override
    public void sendMessage(String subject, String message) {
        System.out.println("SMS: " + subject + " - " + message);
    }
}
@RestController
public class MessageController {

    @Resource(name = "sms")
    private MessageService messageService;

    @RequestMapping("/message")
    public String sendMessage() {
        messageService.sendMessage("Very important:", "Please read this carefully.");
        return "Your message was sent";
    }
}

This behavior is called dependency injection by name.

Now I show you an example of DI by name:

But, if we remove a name parameter from @Resource annotation and then we’ll try to run our example, everything should work as before. Why?

@RestController
public class MessageController {

    @Resource
    private MessageService messageService;

    @RequestMapping("/message")
    public String sendMessage() {
        messageService.sendMessage("Very important:", "Please read this carefully.");
        return "Your message was sent";
    }
}
@Component
public class SmsService implements MessageService {

    @Override
    public void sendMessage(String subject, String message) {
        System.out.println("SMS: " + subject + " - " + message);
    }
}

At the start of application Spring first try to find a bean with messageService name and will fail, next step will be to try to find a bean of the same type, and in our example as SmsService is a subtype of MessageService and as a result of successfully running application, we should get:

Your message was sent

And in the console log:

2016-04-27 10:51:11.006 INFO 9854 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-27 10:51:11.029 INFO 9854 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
SMS: Very important: - Please read this carefully.

 

Leave a Reply