Gradle – Introducing Spring

Introduction

In this tutorial we will be introducing The Spring Framework in our project for managing dependencies. In this series we are using gradle as our build tool but the Spring specific concepts remain the same irrespective of the choice of build tool.

build.gradle

First thing we need to do is, to get the required dependencies of Spring. We are just starting up with dependency management so all we need is spring-context. Update your build as below.

Java Project

In this project we are not going to use commonly used configurations file, which is used to initialize the Spring container. Instead, we will be using purely annotations based approach.

Class Diagram

The class Diagram is pretty simple and self-explanatory. There is a main class Application which uses a reference of Greeting interface to hold its 3 different concrete implementations and prints the 3 different messages.

 

You can take a look at the code below or you can directly go to github repository to access the full source code of the project.

Annotations

We have used a couple of annotation in the project and before looking into the code, it would be better to have some idea about it.

@Configuration

Indicates that Application class here will be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@ComponentScan

An equivalent for Spring XML’s <context:component-scan/> is provided with the @ComponentScan annotation.
In this example we have annotated our Application class with it so, all the classes that are marked with @Component  in this and all subpackages will be scanned, initialized and managed by the Spring container.

@Component

Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Autowired

Marks a constructor, field, setter method or config method as to be autowired by Spring’s dependency injection facilities.

Code Files

Main class which acts as a starting point for the application.

Application.java

 

Next we will code the dependencies of Application.java

Greeting.java

HelloGradle.java

ByeGradle.java

CustomGreeting.java

Execution

IDE

You can simply right click Application.java and run as Java Application.

Build

 

Source Code

You can find the complete source code and updates for this tutorial at github.