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:

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?

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:

 

DI – let’s try to understand it – part 2

To continue our series about DI let’s look at our example of MessageController from previous post – DI – part 1.

Unfortunately there is a problem with our solution.

The MessageController class is dependent, has a tight dependency on the EmailService class. There is a hard connection between these two classes. That means, if we ever change our mind to use TweetService or SmsServce instead of EmailService, we’ll need to change the code this way:

private MessageService messageService = EmailServiceTweetService();

But this solution is no different from previous one. We still have both classes tightly coupled. And this is the time when DI comes handy.

First, we need to annotate TweetService class with Spring @Component annotation to tell Spring to keep instance of TweetService in Application Context, it is a place where Spring keeps objects (called Beans) instantiated.

And instantiating Our TweetService using @Resource annotation when Spring application start.

Running our application and typing http://localhost:8080/message in web browser address bar, we should see:

“Your message was sent”

and

Tweet: Very important: – Please read this carefully.

as a output in console.

 

DI – let’s try to understand it – part 1

In my last post we’ve seen how to setup our project to play with Spring and DI – Creating a simple Spring project. Today we’ll try to understand whole idea about DI backed by few examples.

To continue with our project lets create a package di.example.one under com.programmerscuriosity.springforblogdemo and define MessageService interface that includes one method, sendMessage(String subject, String message).

And then let’s create few classes that implement MessageService interface:

To try out the service let’s create a simple controller class:

If you now run the application and visit http://localhost:8080/message, you should see “Very important e-mail was sent” and in the console you should see the standard print output lines:

Mail: Very important e-mail. – Please read this e-mail carefully.

Hello, Programmer’s curiosity

An example of very simple Spring application that will be extended in next posts to demonstrate Spring framework and DI (dependency injection).

For all examples I’ll be using IntelliJ Idea Ultimate, an ide of my choice for at last 3 years, I love it’s features and productivity speedup that comes with it.

Creating a new Spring project

There are many ways to create a new Spring project. You can create it from scratch or use Spring Initializr plugin for IntelliJ Idea or do it via web Spring Initializr (it creates a zip file, which you can download, unzip and import in your IDE).

SpringInitializr

Next step is to enter few metadata for our project:

Name
It’s the name of the project, e.g. spring-for-blog-demo
Type
It’s the build tool selection to help us compile and package our project. There are a couple of options: Maven and Gradle. I prefer to go with Maven, because of its wide adoption, unless there is a specific need for Gradle.
Packaging
You’ll find two options here – JAR and WAR.
The executable of our application. That JAR or WAR can run standalone, with the standard java -jar command.
Choose JAR packaging here, unless you are using JSP, which needs WAR packaging.
Java version
Our choice is 1.8 here.
Group and Artifact
Group and Artifact uniquely identify a project. Group will identify your project uniquely across all projects, what means that has to be at least as a domain name you control (no problem if you don’t own a domain – just use some name which you feel will be unique), and you can create as many subgroups as you want, e.g. com.programmerscuriosityArtifact uniquely identifies the project inside the group. It is the name of the jar without version. You can choose whatever name you want with lowercase letters and no strange symbols e.g. springforblogdemo.
Version
If you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, …). Don’t use dates as they are usually associated with SNAPSHOT (nightly) builds. For our purpose just leave it untouched.
Description
This is a one line description of the project.
Package
This will be the name of the root package of your application. The common practice for naming it is to join the group and the artifact in some way, e.g. com.programmerscuriosity.springblogdemo.
Remember that “-” isn’t allowed here.

NewProject_metadata

Boot version
This is the version of Spring Boot to use. Normally we’d choose the latest stable release.
Dependencies
This section asks us to choose the dependencies needed. Whatever we choose here will go into the configuration file of the build tool. The build tool will then automatically fetch the needed JARs and put those in the classpath. So, choose just Web for now, and more dependencies can easily be added into the configuration file later.

NewProject_dependencies

Press Next and Finish to create the project in your workspace.

NewProject_structure_and_pom

Running our application at this stage won’t show any results apart from getting an error page (not even defined by us).

WhiteLabelPage

So, lets create a simple controller class and try to display at least simple Hello message.

Create a new package, e.g. com.programmerscuriosity.springforblogdemo.controllers. Inside that package, create a new class, HelloController:

Start your server and type http://localhost:8080/hello in your browser.

hello_programmers_curiosity

And that’s it. We’ve got our base project for further posts about Spring DI ready and running.

 

Spring Framework Modules

spring-overview

The Spring Framework provides about 20 modules which can be used based on an application requirement.

Core Container:

The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:

  • The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.
  • The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.
  • The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.
  • The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime.

Data Access/Integration:

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows:

  • The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.
  • The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
  • The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
  • The Java Messaging Service JMS module contains features for producing and consuming messages.
  • The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs.

Web:

The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules whose detail is as follows:

  • The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.
  • The Web-MVC module contains Spring’s model-view-controller (MVC) implementation for web applications.
  • The Web-Socket module provides support for WebSocket-based, two-way communication between client and server in web applications.
  • The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.

Miscellaneous:

There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is as follows:

  • The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.
  • The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP) framework.
  • The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers.
  • The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients.
  • The Test module supports the testing of Spring components with JUnit or TestNG frameworks.

Spring Framework – Overview

In next few posts I’m going to introduce Spring framework and a couple buzzwords you can find show up when it comes to Spring Framework.

Overview of Spring Framework

Spring is one of the most popular frameworks for developing web and enterprise applications and it is nearly synonymous with Java development in enterprise circles.

It is not a web framework, or a persistence framework, it’s a framework that integrates all kinds of Java technologies/API’s and makes it possible to use them with simple POJO’s.

What is important to know is that Spring does not reinvent the wheel. It provides a nice and elegant way to use existing technologies (such as EJB, Hibernate, JDO, Toplink, JMS, etc).

Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest. You can use the IoC container, with any web framework on top, but you can also use only the Hibernate integration code or the JDBC abstraction layer. The Spring Framework supports declarative transaction management, remote access to your logic through RMI or web services, and various options for persisting your data. It offers a full-featured MVC framework, and enables you to integrate AOP transparently into your software.

Spring is designed to be non-intrusive, meaning that your domain logic code generally has no dependencies on the framework itself. In your integration layer (such as the data access layer), some dependencies on the data access technology and the Spring libraries will exist. However, it should be easy to isolate these dependencies from the rest of your code base.

Dependency Injection and Inversion of Control

Dependency Injection was originally called Inversion of Control (IoC) because the normal control sequence would be the object finds the objects it depends on by itself and then calls them.

Here, this is reversed: The dependencies are handed to the object when it’s created. It delivers a key advantage: loose coupling. Objects can be added and tested independently of other objects, because they don’t depend on anything other than what you pass them. When using traditional dependencies, to test an object you have to create an environment where all of its dependencies exist and are reachable before you can test it. With DI, it’s possible to test the object in isolation passing it mock objects for the ones you don’t want or need to create.

I am going to explain and show usage of DI in spring in further posts.