Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

HI All in this article we see how to Integrate Apache kafka with Spring Boot. As we all know Kafka is a open source messaging queue and it is scalable, fault-tolerant and offer high performance.

Why we use Apache Kafka With Spring Boot

Generally we use Spring Boot with Apache Kafka in Async communication like you want to send a email of purchase bill to customer or you want to pass some data to other microservice so for that we use kafka. In this article we see a simple producer consumer example using kafka and spring boot.

To Integrate apache kafka with spring boot We have to install it. It is open source you can download it easily. Here i am installing it in Ubuntu.

Below are the steps to install the Apache Kafka in Ubuntu machine.

  1. Go to Apache Kafka website
  2. Choose any version from Binary Downloads and download .tgz file.
  3. Extract this .tgz file.
  4. Always remember you have to start zookeper before starting your kafka server.
  5. Go to your bin folder and start zookeper.
  6. Now stay in bin folder and run your kafka server.
Follow Above Steps:

1- Go to Apache kafka website and download the binary version.

apache kafka tutorial

2- Extract this .tgz file using below command.

tar -xvf kafka_2.12-2.5.0.tgz

3- Now Go to your apache kafka bin folder and run below command to start zookeper

./zookeeper-server-start.sh ../config/zookeeper.properties

4- Now run below command to run your kafka server .

./kafka-server-start.sh ../config/server.properties

your Apache kafka server has been started Now we have to create a Spring boot project and Integrate this Kafka server with that. In this Example we create a simple producer consumer Example means we create a sender and a client. Sender Simply send a message a client will consume this message. For creating a Spring boot application we have to follow thw below steps:

  1. Create a Spring Boot Project and add required dependeny in pom.xml file.
  2. Define Kafka related properties in your application.yml or application.properties file.
  3. Producer class that writes message on Kafka Topic.
  4. Create a Consumer class that reds message from Kafka Topic.
  5. Create a Controller class and make a endPoint to send a message using postman or your frontend application.

Follow Above Steps:

1- Create a Spring Boot Project and add required dependeny in pom.xml file. You can also copy this dependency from maven Repositry

<dependency>
 <groupId>org.springframework.boot</groupId> 			 
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.kafka</groupId>
 <artifactId>spring-kafka</artifactId>
</dependency>

2- Define Kafka related properties in your application.yml or application.properties file.

As you know you can either create a application.yml or application.properties file. But many developer prefers application.properties and many will prefers application.yml so i am sharing both the files use which one you like.

application.properties

server.port=8000
spring.kafka.producer.bootstrap=localhost:9092
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.consumer.bootstrap=localhost:9092
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.group-id=group_id

application.yaml

server:
 port: 8000
spring:
  kafka:
     producer:
       bootstrap: localhost:9092
       key-serializer: org.apache.kafka.common.serialization.StringSerializer
       value-serializer: org.apache.kafka.common.serialization.StringSerializer
     consumer:
      bootstrap: localhost:9092
      group-id: group_id
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

If you see in above file here we simplly define a server port as 8000 means my spring boot application is running on 8000 port. And i also define kafka producer and consumer. Here in producer part bootstrap is used to define the Kafka port as i have install kafka in my local machine so i have given the path localhost:9092. In Producer part there are two more keys one is key-serializer and other is value-serializer. If you know about kafka then you know that kafka use key-value for sending message and serialized them so here we use a simple String message so we use StringSerializer .

Now discuss consumer part here bootstrap is same as producer it defines my kafka server path. Here group-id means in Kafka we have to define a topic to send and receive a message. Sender will write the message to this topic and consumer will read the message from this topic. There is a chance that many consumer will read from the same topic so we define a group-id and assign the consumer that group-id. key-deserializer and value-deserializer is used to deserialized the message that send by the producer.

3- Make a Producer class that writes message on Kafka Topic.

package com.vasu.SpringBootKafka.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class Producer {

	private static final Logger logger = LoggerFactory.getLogger(Producer.class);

	private static final String TOPIC = "demo";

	@Autowired
	private KafkaTemplate<String, Object> kafkaTemplate;

	public void sendMessage(String message) {
		logger.info("vvv::  send message");
		kafkaTemplate.send(TOPIC, message);
	}
}

If you see above class code here we define a topic with name demo. And autowired the KafkaTemplate. This class simppy writes the message on the demo topic using KafkaTemplate.

4- Now Make Consumer class that reds message from Kafka Topic.

package com.vasu.SpringBootKafka.service;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class Consumer {

	private static final Logger logger = LoggerFactory.getLogger(Consumer.class);

	@Autowired
	private final ObjectMapper mapper = new ObjectMapper();

	@KafkaListener(topics = "demo", groupId = "group_id")
	public void consume(String message) throws IOException {
		logger.info(String.format("consumed message is= ", message));
	}
}

In above class code we simply consume the message on demo topic and print this message in console. Here we use KafkaListener annotation to read messages from given topic.

5- Now make a Controller class and make a endPoint to send a message using postman or your frontend application.

package com.vasu.SpringBootKafka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.vasu.SpringBootKafka.service.Producer;

@RestController
@RequestMapping("/kafka")
public class KafkaController {

	private final Producer producer;

	@Autowired
	KafkaController(Producer producer) {
		this.producer = producer;
	}

	@PostMapping(value = "/publish")
	public void sendMessageToKafkaTopic(@RequestParam("message") String message) {
		this.producer.sendMessage(message);
	}
}

Here we simplly define a controller class and make a endPoint. Now run your spring boot application and open postman and hit a post request with message parameter and see your eclipse console you will get the message.

spring boot kafka
spring boot kafka

You can also see all the message of this topic in your kafka server console. Just go to your kafka server bin folder and run the below command.

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic demo --from-beginning

Github URL – https://github.com/vasurajput/Spring-Boot-Web/tree/master/SpringBootKafka

You may also like.

How to cache data in springboot

Swagger in Springboot application with Example.

Help Others, Please Share

In this post we will see Spring boot docker Integration. We often hear the word that this project work on my system perfectly i don’t know why this is not working in your system. This is the common issue between developer and tester.

And one more thing that when you develop your project and send it to DevOps team for deployment you see that this team setup the server before deploy your application like they install java version on which you develope your project, Tomcat server, Database Server then they deploy your application.

It is very old feture now days and become a headache for devops team to setup the complete server before deployment. What we can do to reduce this task so here we go here we use Docker.

Docker is a container that contain every dependency of our project and make a image and we share this image to everyone. Now we don’t need to worry about anything we just use this image and run our application. Before use docker you have to download it.

To download docker you can go to official website of docker

https://docs.docker.com/get-docker/

For docker spring boot application we have to define a file with name Dockerfile. And in this file we define some syntax to make a docker image.

We have to follow the below steps for Spring boot docker Integration or to make a docker image of spring boot application and they are:

  1. Create a Simple web spring boot project.
  2. Add required dependency in pom.xml file.
  3. Define Name of your jar in your pom.xml file.
  4. Make Jar of your spring boot Project.
  5. Make a docker file with name Dockerfile.
  6. Run docker command to make docker image.
  7. Run this docker image.

Project description: In this docker spring boot project we simplly make a endPoint and access this endpoint using docker Image.

Project Directoy:

spring boot docker

1- Create a simple web Spring boot project.

2- Add required dependency in pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <scope>runtime</scope>
 <optional>true</optional>
</dependency>

3- Define Name of your jar in your pom.xml file.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
    <finalName>spring-docker</finalName>
</build>

In above syntax see the tag <finalName> this tag is used to define the name of your spring boot jar. When you build your spring boot project you will see the jar name same as that you give in between <finalName> tag.

4- Now make a build of your project using maven install command.

5- Make a docker file with name Dockerfile

FROM java:8
EXPOSE 8080
ADD target/spring-docker.jar spring-docker.jar
ENTRYPOINT ["java","-jar","/spring-docker.jar"]

In above syntax:

From – This is used to define that our project is build on java8 and docker will install this image from dockerhub if it is not present.

EXPOSE – This is used to define that we use 8080 port in docker container.

ADD – This is used to define or jar path. we know that our jar file build inside target folder and jar name is same as that we deifine between <finalName> tag.

ENTRYPOINT – This is used to define the command that run our spring boot application. We know that to run java jar we use java -jar <jarName> command.

6- Run docker command to make docker image

Now open your project in terminal and write the below command to make a docker image.

sudo docker build -t spring-docker.jar .

If you run the above command first time it will take some time to download required images. After run the above command you see the output like.

docker spring boot

To see the list of images in docker we use below command.

sudo docker images
spring boot microservices with docker

7- Run this docker image.

sudo docker run -p 9090:8080 spring-docker.jar

Above command is used to run the docker Image. Here we define 9090:8080 this mean we use 8080 as a docker container port and 9090 as our application port. Means to access your application we use http://localhost:9090/ URL. After run above command you will see the output like below:

spring boot docker tutorial

Now go to your web browser and access your endpoint.

spring boot docker

Github URLhttps://github.com/vasurajput/Spring-Boot-Web/tree/master/SpringbootDocker

You may also like:

spring boot jwt authentication example

Case Statement in SQL example

Help Others, Please Share

In this post we will learn about spring cache. We know that we lose lots of users if our website take more time to load. And there are many reasons that our website take more time to load and some of them are :

  1. Heavy traffic on website.
  2. Using remote database.
  3. Having a complex business logic that load data from more than one source etc.

So what we can do in this situation. We know that most of the time we load data from database and it will take time if we are using any remote database or doing some complex operation with data. So we use spring cache to solve this problem. It stores data in a cache when you fetch data from DB first time. And whenever we get request for data so we return data from cache we do not hit the DB every time.

And if we update Our database then Spring boot cache provides many useful annotation so that we can manage our cache data accordingly.

Spring boot cache provides many annotation and some of them are:

Annotation Description Syntax
@Cacheable This annotation is used to tell that we are storing this method data into cache. We define a name for cache for uniquely identify cache.@Cacheable(cacheNames = “studentCache”)
@CacheEvictThis annotaion is used to remove value from cache@CacheEvict(value = “studentCache”, allEntries = true)
@CacheConfigThis annotaion is used to enable the cache at class level. We define this annotation at class level now you can use @Cacheable without cacheName.@CacheConfig(cacheNames = “studentCache”)
@CachePutThis annotaion is used to add or update the cache data.@CachePut(cacheNames = “studentCache”)
@CachingThis annotation is used at method level with multiple annotaion of same type@Caching(evict =
@CacheEvict(value = “studentCache”, allEntries = true))

To Use cache in Spring boot we have to follow the below Steps:

  1. Add required dependency in pom.xml file.
  2. Enable cache using @EnableCaching annotation in your main class.
  3. Create a controller class and make some end point.
  4. Create a service class and use Spring boot cache annotation here.

Project Description: In this Project we simply create a Student Model Class. And in this class we perform operation like add, delete, update, find student and see how we use cache for this scenario.

Project Direcotry:

Spring boot cache tutorial with example

1- Add required dependency in pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2- Enable cache using @EnableCaching annotation in your main class.

package com.vasu.SpringBootCache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import com.vasu.SpringBootCache.dao.StudentDAO;
import com.vasu.SpringBootCache.model.Student;

@EnableCaching
@SpringBootApplication
public class SpringBootCacheApplication implements CommandLineRunner{
	
	@Autowired
	private StudentDAO dao;

	public static void main(String[] args) {
		SpringApplication.run(SpringBootCacheApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		for (int i=0;i<10;i++) {
			Student student = new Student(i+0L,"name " + i, "emailId " + i, "address "+i);
			dao.save(student);
		}
		
	}

}

3- Create a controller class and make some end point.

package com.vasu.SpringBootCache.controller;

import java.util.List;

import javax.websocket.server.PathParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.vasu.SpringBootCache.model.Student;
import com.vasu.SpringBootCache.service.StudentService;

@RestController
public class StudentController {
	private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

	@Autowired
	private StudentService service;
	
	@GetMapping("/")
	public List<Student> getAllStudent() {
		return service.getAllStudent();
	}
	
	@GetMapping("/deleteById/{studentId}")
	public List<Student> deleteById(@PathVariable("studentId") Long studentId) {
		logger.info("vvv::  studentId= "+studentId);
		List<Student> response = service.deleteById(studentId);
		return response;
	}
	
	@GetMapping("/save/{id}/{name}/{email}/{address}")
	public List<Student> saveStudent(@PathVariable("id") Long id,
			@PathVariable("name") String name,
			@PathVariable("email") String email,
			@PathVariable("address") String address) {
		return service.save(new Student(id,name,email,address));
	}
	
	@GetMapping("/clearCache")
	public String clear() {
		service.clearCache();
		return "Cache has been cleared";
	}
}

4- Create a Repositry class that extends JpaRepository for CRUD operation.

package com.vasu.SpringBootCache.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.vasu.SpringBootCache.model.Student;

@Repository
public interface StudentDAO extends JpaRepository<Student, Long>{

}

5- Create a service class and use Spring boot cache annotation here.

package com.vasu.SpringBootCache.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.vasu.SpringBootCache.dao.StudentDAO;
import com.vasu.SpringBootCache.model.Student;

@Service
@CacheConfig(cacheNames = "studentCache")
public class StudentService {
	private static final Logger logger = LoggerFactory.getLogger(StudentService.class);
	
	@Autowired
	private StudentDAO dao;
	
	@Cacheable(cacheNames  = "studentCache")
	public List<Student> getAllStudent() {
		logger.info("vvv:: getAllStudent calling" );
		return dao.findAll();
	}
	
	@Caching(evict = 
			@CacheEvict(value = "studentCache", allEntries = true))
	public List<Student> deleteById(Long id) {
		logger.info("vvv:: deleteById calling" );
		dao.deleteById(id);
		return dao.findAll();
	}
	
	@CachePut(cacheNames = "studentCache")
	public List<Student> save(Student student){
		dao.save(student);
		return dao.findAll();
		
	}
	
	
	@CacheEvict(value = "studentCache", allEntries = true)
	public void clearCache() {
		logger.info("vvv::  cache has been clear");
	}
}

Now you have succesfully created a spring boot project with cache. Now run your application. After run when first time you call http://localhost:8080/ url you will get complete list of Student and check console here you will see JPA query log . Now clear log and again hit the URL now see your console you will not get any JPA log here because second time data will be received from cache not DB.

Same hit delete URL with ID http://localhost:8080/deleteById/21 and after delete Student again hit getAllUser ( http://localhost:8080/ ) URL you will again see JPA query in console because we evict cache while call delete method. Now play woth your code and see changes.

GitHub URLhttps://github.com/vasurajput/Spring-Boot-Web/tree/master/SpringBootCache

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

Profiles in Spring boot application

How to deploy spring boot application on docker 

Spring Boot with Apache kafka.

Swagger2 in Spring Boot

Help Others, Please Share

As we know Angular is a structural framework for web-apps. And it is used to perform operation on front end like parsing Json data and display in well format with help of HTML or Bootstrap Component , make http Calls to external API etc. To create a project with Angular JS you should know how to create a spring boot application with JSP for this follow my post ( Click Me ) . In this post we see how to integrate Angular JS in our Spring boot application. There are two ways you can use Angular JS in your application.

  1. Using Angular CDN in your web page
  2. Using Angular webjar in your pom.xml file

In this we will see how to integrate Angular JS with Spring boot using Angular webjar dependency. There are some steps that you have to follow to integrate Angular with Spring boot.

  1. Create a Spring Boot Project.
  2. Add Angular dependency in your pom.xml file.
  3. Create a JSP File ( In this example we create index.jsp ).
  4. Add Jsp Prefix in application,properties file.
  5. Create a Angular Controller and use it in your index.jsp file.
  6. Create a Controller class to provide end point to access your jsp Page.

Project Directory:

Angular Js with Spring boot

Now Follow above steps and create a Spring boot web porject.

2- Add below dependency in your pom.xml file.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>4.1.1</version>
</dependency>

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>angularjs</artifactId>
   <version>1.7.0</version>
</dependency>

<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>jquery</artifactId>
   <version>3.3.1</version>
</dependency>

3- Create a JSP File

<%-- 
    Document   : index
    Created on : 21 Aug, 2018, 2:54:40 PM
    Author     : Vasu Rajput
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html ng-app="myapp">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link href="webjars/bootstrap/4.1.1/css/bootstrap.min.css"
              rel="stylesheet">
        <script src="webjars/angularjs/1.7.0/angular.min.js"></script>
        <script src="js/mycontroller.js"></script>
    </head>
    <body ng-controller="myctrl">

        <h1><center>Spring Boot With Angular Js</center></h1>
        <div class="jumbotron">
            <center><u>{{ title }}</u></center>
            <div class="col-md-6">
                Name <input type="text" class="foem-control" ng-model="myAngularModel">
                </br>
                Output: {{myAngularModel}}
            </div>
        </div>


        <script src="webjars/jquery/3.3.1/jquery.min.js"></script>
        <script src="webjars/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    </body>
</html>

If you see this index.jsp file look inside head tag we have given the path of our bootstrap, JS and Angular jar to access there feature. And also look that we have also add mycontroller.js file where we define our Angular JS controller. And in this Index.jsp file if you see html starting tag then we have added a ng-app tag that we use in Js file inside body starting tag we use ng-controller tag where we define our controller name.

4- Add Jsp Prefix in application,properties file.

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

5- Create a Angular Controller and use it in your index.jsp file.

var app = angular.module('myapp', []);
app.controller('myctrl', function ($scope) {
    $scope.title = "Angular Two Way Binding Example";
});

If you have basic knowledge about Angular Js then you will know that we just define a simple Angular Controller in this file. Here look at module name that is myapp it is the same name that we define in html starting tag. And look at controller name myctrl that we define in body starting tag in our index.jsp file.

6- Create a Controller class to provide end point to access your jsp Page.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vasu.SpringWithAngularJs.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Vasu Rajput
 */
@Controller
public class DemoController {

    @GetMapping("/")
    public ModelAndView myFirstModel() {
        ModelAndView model = new ModelAndView("index");
        return model;
    }
}

In above file we simply define a controller ( / ) endPoint that return our index file.

Now Steps are over and you have successfully created a Spring boot Application with Angular JS. Now if you run your application you will get the output like .

Angular Js with Spring boot

Github URL – https://github.com/vasurajput/Spring-Boot-Web

Help Others, Please Share

As we know every project required some documentation so that we get some help about the project. There is two option either you write yourself in a notepad or excel file about the project like details of endPoints in the project or use some tools that do documentation for you. I think second point is better we use some tool, so spring boot provide us a open source tool named Swagger2 for documentation. To use swagger2 in our application we have to follow below steps:

  1. Add required dependency in your pom.xml file.
  2. Create a Bean of Docker and provide your base package name .
  3. Create a controller class and define some end points for which you want documentation information.
  4. Run your application and hit the swagger2 URL.

Follow above Steps:

1- Add required dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>
	
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger2</artifactId>
 <version>2.9.1</version>
</dependency>

<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger-ui</artifactId>
 <version>2.9.1</version>
</dependency>

2- Create a Bean of Docker and provide your base package name .

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SwaggerSpringBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SwaggerSpringBootApplication.class, args);
	}
	
	  @Bean
	    public Docket productApi() {
	        return new Docket(DocumentationType.SPRING_WEB.SWAGGER_2).select()
					.apis(RequestHandlerSelectors.basePackage("com.example.demo")).build();
	    }

}

3- Create a controller class and define some end points for which you want documentation information.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

	@GetMapping("/")
	public String entryPoint() {
		return "This is entry point";
	}
	
	@GetMapping("/api1")
	public String api1() {
		return "This is entry point";
	}
	
	@GetMapping("/api2")
	public String api2() {
		return "This is api2";
	}
}

4- Run your application and hit the swagger2 URL i.e.

http://localhost:8080/swagger-ui.html

After hitting the URL you will get a UI that dispplay the information about your end points and you can also test your api.

Complete Code on GitHub: Swagger2 in Spring Boot

Help Others, Please Share

As we know in every web application we define some property that we use in our code in a common file so that if we want to change the value in future we have to do changes in only one file. In Spring boot we define our property in application.properties file and to read this property from application.properties file spring boot provides two methods.

  1. Using @Value annotation.
  2. Using @ConfigurationProperties annotation.

In this blog we see both the methods. First we will see how to read property using @value annotation. To read the value using @Value annotaion first we define the property name in application.properties file say example we define a property name myname and value as vasu so to read myname property using @Value annotaion we use below syntax:

application.property

myname=vasu
@Value("${myname} ")
private String name;

Now Our class will look like below:

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NameController {

	@Value("${myname} ")
	private String name;
	
	@GetMapping("/")
	public String test() {
		return "My Name is "+name;
	}
}

Now if you run your application and hit the URL http://localhost:8080/ you will get the response like below:

My Name is vasu

But it is a bad practice to read property values using @Value annotation. Suppose we have 10 property so to read this 10 property we have to use @Value annotation 10 times. So to avoid this we use @ConfigurationProperties annotaion.

To use @ConfigurationProperties annotation we define a class and annotated this class with @ConfigurationProperties anotation and we use a prefix with this @ConfigurationProperties annotaion like @ConfigurationProperties(“vasu”) now in our application.properties file we define property with this prefix like below:

vasu.value=true
vasu.message= coding is fun
vasu.number=1

Now create a class that annotated with @ConfigurationProperties(“vasu”) annotaion:

package com.example.demo.model;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("vasu")
public class MyModel {

	private boolean value;
	private String message;
	private int number;

	public MyModel() {
		super();
	}

	public boolean isValue() {
		return value;
	}

	public void setValue(boolean value) {
		this.value = value;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

}

Now Autowired this class in your controller and read the property file using getter method like below:

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.MyModel;

@RestController
public class NameController {

	@Value("${myname} ")
	private String name;
	
	@Autowired
	private MyModel model;
	
	@GetMapping("/")
	public String test() {
		return "My Name is "+name
				+", i am always "+model.isValue()
				+", my messgage to you is  "+model.getMessage()
				+", i want to be number  "+model.getNumber();
	}
}

Now if your run your application and hit the URL http://localhost:8080/you will get the response like below:

My Name is vasu , i am always true, my messgage to you is coding is fun, i want to be number 1

Complete code on GitHub: Read Property in Spring Boot

Help Others, Please Share

As we know we can use many database with spring boot application like MySQL, MongoDB, SQL Server etc. But if we don’t have any database installed in our machine then we can use this embedded database of spring boot. Spring boot provide us this embedded database for performing task. But it is not a good choice for production because this database is accessible only when our application is running if we stop our application it will automatically off the H2 database. To see how to configure h2 database in spring boot we have to follow the below steps:

  1. Add the required dependency in your pom.xml file
  2. Enable the H2 database by defining property in your application.properties file.
  3. Create an Entity using JPA named as student.
  4. Run your application and hit the H2 console URL, Change the JDBC URL in H2 UI to jdbc:h2:mem:testdb and connect to database.

Follow above Steps:

1- Add the required dependency in your pom.xml file

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <scope>runtime</scope>
 <optional>true</optional>
</dependency>

<dependency>
 <groupId>com.h2database</groupId>
 <artifactId>h2</artifactId>
</dependency>

2- Enable the H2 database by defining property in your application.properties file.

server.port=8081
   
spring.h2.console.path=/h2-console
Spring.h2.console.enabled=true

Spring.jpa.show-sql=true
spring.datasource.url=jdbc:h2:mem:testdb


3- Create an Entity using JPA named as student.

package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "studentId")
	private long id;

	private String name;

	private String emailId;

	public Student() {
		super();
	}

	public Student(long id, String name, String emailId) {
		super();
		this.id = id;
		this.name = name;
		this.emailId = emailId;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

4- Run your application and hit the H2 console URL, Change the JDBC URL in H2 UI to jdbc:h2:mem:testdb and connect to database.

As we define port as 8081 and h2 console path as /h2-console in application.properties file. So you have to hit the below URL:

http://localhost:8081/h2-console

Now when you hit the above URL you will get a UI like below, change the JDBC URL to jdbc:h2:mem:testdb and click on connect you will get the table named as Student at we create using JPA.

h2 database spring boot
h2 database spring boot

Complete code on GitHub: Spring Boot H2 Database

You may also like:

Profiles in Spring boot application

Swagger2 in Spring Boot

Spring Boot Security With MySql

Spring boot security using JWT ( JSON WEB TOKENS ).

File Upload in Spring Boot

Help Others, Please Share

We always need some tool that is used for monitoring our application. Spring boot provides Actuator for monitoring the application. It tells us the complete status of our application like status of our application, Information about our application, Beans detail of application and many more. We can see the actuator endPoint using hit the below URL

http://localhost:8080/actuator

For using this actuator endPoint you have to add the below dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Now run your application and hit the above given URL you will get the response like below:

By default only health and info end point are available using HTTP if you want to show all the endPoint using HTTP, you have to add below property in your application.properties file.

management.endpoint.shutdown.enabled=true
management.endpoints.web.exposure.include=health,info,metrics,env,mappings,beans,shutdown

No hit the URL again now you will get the response like below:

By default if you hit the health or info URL it will give only specific information like below:

But if you want to see the complete health status and give information about your application using info endPoint you have to add the below property in your application.properties file.

management.endpoint.health.show-details=always

info.appInformation.name=Spring Actuator Example
info.appInformation.description=This is First Spring Boot Actuator Application Example
info.appInformation.version=1.1.1

Now hit the /health and /info URL again you will get the response like below:

Spring boot Actuator provide /shutdown endPoint using which we can shutdown our application. This is a post request if you hit the /shutdown URL with POST method your application will shutdown and you will get the response like below:

We know by default all the actuator endPoints are available on /actuator endPoint but if we want to change this URL and port we have to add the below property in application.properties file:

management.endpoints.web.base-path=/vasu
management.server.port=9009

Now our actuator endPoints are available on below URL:

http://localhost:9009/vasu/

Complete Code on GitHub: Actuator SpringBoot

Help Others, Please Share

we know database connectivity is the most interesting part of any web application. As we already know how to use Mysql Database in Spring Boot application ( CLICK ME ), but sometime we need more than one database to interact with in our single application. So it is very easy to use multiple database in a single application. In this blog we see how to connect two different MySql database in Spring boot application. For that we have to follow the below steps:

  1. Add required dependency in your pom.xml file.
  2. Create Two Database named database1, database2 and create a table named testing in both the databases.
  3. Define MySql property for both the database in your application.properties file.
  4. Define a configuration class and initialise jdbctemplate for both the databases.
  5. Create a Service class and Autowired both the initialize jdbctemplate in that class and perform query to save data in different databases tables.
  6. Create a controller class that is used to declare an rest endPoint .

Follow Above steps:

1- Add required dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <scope>runtime</scope>
 <optional>true</optional>
</dependency>

<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <scope>runtime</scope>
</dependency>

2- Create Two Database named database1, database2 and create a table names testing in both the databases.

create database1;

use database1;

CREATE TABLE `testing` (
  `id` int(2) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

create database2;

use database2;

CREATE TABLE `testing` (
  `id` int(2) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
)


3- Define MySql property for both the database in your application.properties file.

#Configuration for First Database
database1.datasource.jdbc-url=jdbc:mysql://localhost:3306/database1
database1.datasource.username=vasu
database1.datasource.password=12345@
database1.datasource.driver-class-name=com.mysql.jdbc.Driver


#Configuration For Second Database
database2.datasource.jdbc-url=jdbc:mysql://localhost:3306/database2
database2.datasource.username=vasu
database2.datasource.password=12345@
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

4- Define a configuration class and initialise jdbctemplate for both the databases.

package com.example.demo.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@org.springframework.context.annotation.Configuration
public class Configuration {

	/* ********* For Database 1 *********** */
	@Bean(name = "datasource1")
	@ConfigurationProperties(prefix = "database1.datasource")
	@Primary
	public DataSource dataSource1() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "db1_template")
	public JdbcTemplate database_1_template(@Qualifier("datasource1") DataSource db1) {
		return new JdbcTemplate(db1);
	}
	
	
	/* ********* For Database 2 *********** */
	@Bean(name = "datasource2")
	@ConfigurationProperties(prefix = "database2.datasource")
	public DataSource dataSource2() {
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name = "db2_template")
	public JdbcTemplate database_2_template(@Qualifier("datasource2") DataSource db2) {
		return new JdbcTemplate(db2);
	}
}

5- Create a Service class and Autowired both the initialize jdbctemplate in that class and perform query to save data in different databases tables.

package com.example.demo.service;

import javax.transaction.Transactional;

import org.hibernate.annotations.common.util.impl.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class MainService {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(MainService.class);
	
	private static final String query = "insert into testing(id,name) values(?,?)";

	@Autowired
	@Qualifier("db1_template")
	private JdbcTemplate template_database_1;
	
	@Autowired
	@Qualifier("db2_template")
	private JdbcTemplate template_database_2;
	
	@Transactional
	public int save() {
		try {
			int insertDB1Status = template_database_1.update(query, new Object[] {1,"vasu rajput"});
			logger.info("insertDB1Status= "+insertDB1Status);
			
			int insertDB2Status = template_database_2.update(query, new Object[] {2,"vishu rajput"});
			logger.info("insertDB1Status= "+insertDB1Status);
			
			return 1;
		} catch (Exception e) {
			logger.error("Exception: "+e);
			return 0;
		}
	}
}

6- Create a controller class that is used to declare an rest endPoint .

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.MainService;

@RestController
public class MainController {

	private static final Logger logger = LoggerFactory.getLogger(MainController.class);

	@Autowired
	private MainService service;

	@GetMapping("/")
	public String test() {
		try {
			int saveStatus = service.save();
			logger.info("saveStatus= " + saveStatus);
			if (saveStatus == 1) {
				return "Nice Try Champ !!";
			} else {
				return "Some Technical Error Please Try again";
			}
		} catch (Exception e) {
			logger.error("Exception: " + e);
			return "Some Technical Error Please Try again";
		}
	}
}

Complete Code on Github: Multiple Database SpringBoot

Help Others, Please Share

As we know in microservice architecture we have many application and every application have some end points. But it is difficult if we integrate our application with any front end technology. For that we have to define many end point and at some point it becomes hard to maintain the endpoints. So we have to give a common API address to other front end technology and that is also secure because now our Zuul API gateway address is open to others and our rest of application end Points are secured on private IP server . So spring cloud provide Netflix zuul Server for this that is used for routing the other application end Points. To use Netflix Zuul API gateway we have to follow below steps:

  1. Add required dependency in your pom.xml file.
  2. Use @EnableZuulProxy annotation in your main class.
  3. Register this Zuul API gateway application With Eureka Server.
  4. Provide routing endPoints property in your application.properties file.
  5. Run Eureka Server and all other application and use your zuul gateway url to access all other application end Points.

Summary of Project: In this Project we have created Four Application.

  1. An Eureka Server application that is used to monitor other application.
  2. An Student application that is registered with Eureka Server and have a GET end Point name /student.
  3. An Teacher application that is registered with Eureka Server and have a GET end Point name /teacher
  4. An Zuul API Gateway that is also register with Eureka Server and provide URL using which we can access Teacher and Student end points.

First Three Steps of Project Summary we have already know how to create if not than see my blogs on Microservices ( CLICK ME ). In this we focus on Fourth point how to create zuul API gateway. So now flow above given steps:

1- Add required dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

2- Use @EnableZuulProxy annotation in your main class.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableEurekaClient
@EnableZuulProxy
@SpringBootApplication
public class AccountServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(AccountServiceApplication.class, args);
	}

}

3- Now in this steps we have to register our Zuul API gateway with Eureka Server and also provide routing to others endPoint. So this use below properties in your application.properties file.

server.port=8082
spring.application.name=gateway-service
eureka.client.service-url.default-zone=http://localhost:8761/eureka

zuul.routes.student-service.path=/studentGateway/**
zuul.routes.teacher-service.path=/teacherGateway/**

In the above properties zuul.routes.student-service.path

zuul.routes is fixed student-service is the name of application that you have defined for Student application in your Student application.properties file after that append path and in value you can give any prefix that you want here we give /studentGateway/** Now our property become

zuul.routes.student-service.path=/studentGateway/**

Same is For teacher property Now you have to hit the below URL for access Student and Teacher end point response.

To Access Student URL hit below URL

http://localhost:8082/studentGateway/student

To Access teacher URL hit below URL

http://localhost:8082/teacherGateway/teacher/

If You want to give any prefix also you can add that in your Zuul API gateway application.properties file.

zuul.prefix=/gatewayAPI

Now your application.properties look like

server.port=8082
spring.application.name=gateway-service
eureka.client.service-url.default-zone=http://localhost:8761/eureka

zuul.prefix=/gatewayAPI
zuul.routes.student-service.path=/studentGateway/**
zuul.routes.teacher-service.path=/teacherGateway/**




Now your Student and Teacher URL become.

http://localhost:8082/gatewayAPI/studentGateway/student
http://localhost:8082/gatewayAPI/teacherGateway/teacher/

Complete Code On GitHub : Zull Gateway Routing

Help Others, Please Share