How to Create Annotation based Spring Application

Introduction

We will see how to create annotation based Spring application. We will use here H2 database to perform database activities using Spring JDBC Template. We will not use any XML configuration here or zero XML configuration. We will also see how to run this stand-alone Spring application using main method. This application is totally Java based configuration.

If you want you can also convert this application as web based application using Spring framework.

Prerequisites

Spring 5.1.7, JDk 1.8, Eclipse 4.9, H2 1.4.196, Gradle 4.10.2

Example with Source Code

We will create stand alone Spring application to show how annotation based application works in Spring framework.

Creating Project

Create Gradle based project called spring-annotation in Eclipse and the project structure should looks as similar to below figure:

Creating Insert Script

Create below insert-data.sql script and put it under src/main/resources/sql directory.

insert into `item`(`item_id`,`item_name`,`item_desc`,`item_price`)
values (1,'CD','CD is a compact disk',100),
(2,'DVD','DVD is larger than CD in size',150),
(3,'ABC','ABC test description',24),
(4,'XYZ','XYZ test description',25.32),
(5,'CD Player','CD player is used to play CD',30.02),
(6,'New Item1','New Item1 Desc',125);

Notice how did we map the data types as well otherwise you will get compiler error or runtime exception.

Creating Spring Repository Class

We need to create Spring reposiroty or DAO class to interact and perform operations on database. Ideally we should write code to interfaces to make the components loosely coupled but for this example we will create only class.

We have used annotation @Repository to auto-pickup by container. You can also use @Component annotation if you don’t want to use @Repository.

In the above class we used AnnotationConfigApplicationContext to load our component classes. We load Config class as we have declared the base package on this class and this class itself is annotated with @Configuration. Therefore we will get all required beans from this class.

We have retrieved the service bean to fetch all items and displaying them on console.

Running the Application

When you run the above main class as a Java Application, then you will see the following output: