Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

Java toLowerCase function of string converts the given string into lower case. Return type of this function is String.

For Example if i have a string like “I Like Java Programming Language” and i want to convert this string into lower case then i will use toLowerCase function of String.

package javadream;

import java.util.Locale;

public class JavaDream {

	public static void main(String[] args) {
		 String str = "I Like Java Programming Language";
		 String lowerCase = str.toLowerCase();
		 System.out.println(lowerCase);
	}
}

Output

tolowercase java

As toLowerCase function java also provides toUpperCase function. This function is used to convert given string into upper case.

toUpperCase Function

package javadream;

import java.util.Locale;

public class JavaDream {

	public static void main(String[] args) {
		 String str = "I Like Java Programming Language";
		 String upperCase = str.toUpperCase();
		 System.out.println(upperCase);
	}
}

Output

You may also like

CASE Statement in MySQL Example

Spring Boot Complete Tutorial from Zero to Hero

Refrence:

Java Official Documents

Help Others, Please Share

In this post we will see CASE Statement in SQL. CASE Statement is like if-else block of programming language. Like in programming language we perform some task if the condition is true if not then we perform other task in else block same functionality is used for CASE statement. We use CASE when we have to perform some task based on the condition.

Syntax of Case statement in MySQL is like :

CASE
WHEN SOME_CONDITION THEN CONDITION_RESULT
WHEN SOME_CONDITION THEN CONDITION_RESULT
ELSE ELSE_CONDITION_RESULT
END

For using CASE Statement in SQL just take an Example suppose If i have a table of Student that contains two column name, course. Now i want that if the course is CSE then i will display you have exam tomorrow and for other courses i want to display Enjoy you don’t have exam tomorrow. So in this case we use CASE function.

Student Table:

CASE Statement in SQL

Now we will use CASE function in above table. The query will be like below.

select name,course,
case
when course = "CSE" then "you have Exam tomorrow"
else "Enjoy the day you don't have exam"
end as ExamStatus
from student;
SQL CASE Statement

You may also like:

How to database backup in MySQL

MySQL Dates and Times function example

Integration of Springboot with MySQL Database Example.

Refrences:

MySQL official docs for functions.

Help Others, Please Share

In this post we will see MySQL dates and times related examples. As we know MySQL provide some functions using which we can get date and time and related data. As we know there are many scenario when we have to get date and time and some time we have to perform some mathematics with dates and times also so MySQL inbuilt function is very helpful in all of this . Some of the inbuilt MySQL Dates and Times functions are.

  1. now()
  2. curdate()
  3. curtime()
  4. year()
  5. month()
  6. monthname()
  7. day()
  8. dayname()
  9. dayofmonth()
  10. dayofweek()
  11. dayofyear()

1. now()

now() is a inbuilt function provided by MySQL. This function provide us current date and time of server.

2. curdate()

curdate() is a inbuilt function provided by MySQL. This function provide us current date of the server.

3. curtime()

curtime() is a inbuilt function provided by MySQL. This function provide us current time of the server.

date and time MySQL

4. year()

year() function is used to get the year from the current date. We can use now() and curdate() function with year() to fetch the year.

year() in MySQL

5. month()

This function is used to get the month from the current date of server.

6. monthname()

This function is used to get the name of month from the current date of server.

mont() in MySQL

7. day()

This function is used to get the day from the current date of server. There are many other functions for getting details of day and that are dayname(), dayofmonth(), dayofweek(), dayofyear().

day() in MySQL

You may also like :

How to take databackup in MySQL using commandLine.

MySQL Basic Commands.

Reference :

MySQL official Document for Dates and Times

Help Others, Please Share

In this Post we will see how to take MySQL database backup using command line. First we have to login our MySQL using below command and enter password.

mysql -u vasu -p

Now to show all databases we use below command.

show databases

Now above command will show all the databases list that are present in your MySQL. Now it’s time to backup some database. So to take backup of any database we will use below syntax.

Syntax :
mysqldump -u {Mysql UserName} -p {databaseName} > {location where you want to save}\{Name What you want to give}.sql

Example
mysqldump -u vasu -p myFirstDB > /usr/local/myFirstBackup.sql


After this command hit enter it will ask your Mysql Password Enter the password and you will successfully get the database backup.

Now After getting Backup we have to use it in mysql ,So for storing this backup in mysql we use the command source

Use the Following Syntax for restore database backup

Syntax:

source { location of database backup file }

Example:

source /usr/local/myFirstBackup.sql

If You want to get mysql database backup using cmd in windows then use following steps

First Go to to the bin folder of your mysql using the following path

  1. C:\Program Files\MySQL\MySQL Server 5.7\bin
  2. Now use ALT + D
  3. Now when address bar is highlighted, type cmd in the bar.
  4. Now Use the same command you use above
  5. mysqldump -u root -p yourdatabasename > c:/myfirstbackup.sql
  6. source C:\myFirstBackup.sql

Note : while you using cmd it might be possible that you get the Access is denied error, To resolve this open cmd  via Run as administrator , now use command it will work .

You may also like

How to create user in MySQL

Help Others, Please Share

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

Before Use Kafka Let’s see a live scenario example for why we use Apache Kafka

Suppose we buy a product from an online store and we want to give feedback on this product.

  1. If our application uses synchronous calls to update the feedback then the user has to wait until we get the response from our APIs. This is a bad practice because the user does not care about the background process but he waits for a success message because of our Apis call.

what if an exception occurs while calling Apis then the user gets a message like something went wrong please try again after waiting for 4-5 second( time to get a response from Apis).

2. If our application uses an Asynchronous call to update feedback. In this case, the user gets a response message immediately and the Apis call works in the background.

What if an exception occurs while calling this Apis. And we have already shown the successful response to the user now what to do.

So both the synchronous and Asynchronous methods will not work in this scenario. So to overcome this situation we use a messaging queue. If we use message queue then when we get a request for feedback update we put this request payload on a topic and after getting acknowledgment we return a success message to the user.

Note: Getting acknowledgment from the message queue will take less time as compared to getting a response after a synchronous Apis call.

And if any exception occurs in this scenario while Apis call we can implement retry logic in the message queue.

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 Apache Kafka on the Ubuntu machine.

  1. Go to the Apache Kafka website
  2. Choose any version from Binary Downloads and download the .tgz file.
  3. Extract this .tgz file.
  4. Always remember you have to start zookeeper before starting your Kafka server.
  5. Go to your bin folder and start zookeeper.
  6. Now stay in the 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 sends a message a client will consume this message. For creating a Spring boot application we have to follow the below steps:

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

Follow Above Steps:

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

<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 an application.yml or application.properties file. But many developers prefer applications. properties and many will prefer 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 the above file here we simply define a server port as 8000 means my spring boot application is running on an 8000 port. And I also define Kafka as producer and consumer. Here in the producer part bootstrap is used to define the Kafka port as I have to install Kafka in my local machine so I have given the path localhost:9092. In the Producer part, there are two more keys one is key-serializer and the other is value-serializer. If you know about Kafka then you know that Kafka uses key-value for sending messages and serialized them so here we use a simple String message so we use StringSerializer.

Now discuss the consumer part here bootstrap is the same as a 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. The sender will write the message to this topic and the consumer will read the message from this topic. There is a chance that many consumers will read from the same topic so we define a group-id and assign the consumer that group-id. key-deserializer and value-deserializer are used to deserialize the message that sends 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 the above class code here we define a topic with a name demo. And autowired the KafkaTemplate. This class simply 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 the above class code, we simply consume the message on the demo topic and print this message in the console. Here we use KafkaListener annotation to read messages from a 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 simply define a controller class and make an 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 messages 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

x