Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

We know that in Monolithic application complete Code is at one place, in MicroService we divide this big monolithic application in small small microservices.

Suppose we create a separate application named EurekaClient-1 with some rest end points and host this application on Eureka Server so we don’t need to worry about details of this application.

To create this separate client application names EurekaClient-1 we have to follow below steps:

1- Add below 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>

2- Enable Eureka client using @EnableEurekaClient in your main class.

@EnableEurekaClient
@SpringBootApplication
public class EurekaClient1Application {
   public static void main(String[] args) {
	SpringApplication.run(EurekaClient1Application.class, args);
	}
}

3- Give this application name, and a Port on which it will run, and path of the Eureka Server.

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

4- Create Controller Class and make some end points.

@RestController
public class ClientController1 {

	@GetMapping("/client1")
	public String client1() {
		return "I am client 1";
	}

}

Run your application and see your eureka server you will see your application hosted there.

Note: Before running your application make sure your eureka server is running.

Now access below url for getting your end point response

http://localhost:8081/client1

Help Others, Please Share

Eureka Server is used to monitor all the application. With the help of Eureka Server we don’t need to worry about information like which application running on which port and how many instances of application are running, all this are take cares by Eureka Server.So to Create a Eureka Server we have to follow below steps:

  1. Add required dependency in you pom.xml file
  2. Enable Your main class as a Eureka Server using @EnableEurekaServer annotation.
  3. Define applicationName and portNo in application.properties file.
  4. By Default Eureka act as a client but now we want this application to work as Eureka Server so we make Eureka registry as false in application.properties file.

1- Add the Eureka Server dependency in your pom.xml file.

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

2- Enable Eureka Server by using @EnableEurekaServer annotation in your main class.

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
   public static void main(String[] args) {
	SpringApplication.run(EurekaServerApplication.class, args);
	}
}

3- By Default Eureka Server application running as a client so if we have want to act this application as a server then we have to add below properties in application.properties file

 spring.application.name=netflix-eureka-server
 server.port=8761
 eureka.client.register-with-eureka=false
 eureka.client.fetch-registry=false

In above application.properties file

server.port define the port on which Eureka Server running in our case it is running on 8761 port so to access your eureka server just hit below URL in your browser.

http://localhost:8761/

Help Others, Please Share

In this post we will see spring boot profiles. We know that our application go through many phases like development, testing, production. So for them we have to do configuration accordingly.

Spring boot provides profile feature for this. So Using spring boot profiles we can use different properties in different phases. Suppose i have three environment development, testing, production.

Now if we want that developer will use property defined for developers and tester will use properties defined for tester and in production our application use properties for production environment.

To see How to set profiles in spring boot we have to follow the below steps:

Project Structure:

How to Use Profile in Spring BOOT - JavaDream

1- Add below dependency in your pom.xml file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</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>

2- create application.properties for development and testing phase syntax would be like

application-{Your-Phase-Name}.properties

Eg: application-dev.properties      // this is for development phase
    application-test.properties     //this is for testing phase

application-dev.properties – In this property file we will define the property that will be used by the developer. Suppose i define only one property with key as name and value as development.

name=development environment 

application-test.properties – In this property file we will define the property that will be used by the tester. And here we define only one property same as in developer property with key as name and value as testing.

name=testing environment

3- application.properties – This is our main property file here we define which profile need to be activated. Suppose currently developer is working on the application so our application should fetch property from application-dev.properties file so for this we have to write below property in our application.properties file.

spring.profiles.active=dev

Above syntax define that our application-dev.properties is activated. Now suppose the application is in testing phase so now tester wants that his property will be fetched so for using testing profile we will use below property in our application.properties file

spring.profiles.active=test

Now Check this using code suppose i want to print the name property value that i have defined in both the dev and test property. Suppose first i want to print the name from dev property than in my main application.properties file i will use spring.profiles.active=dev

And when we have to print the name from test property than in my main application.properties file i will use spring.profiles.active=test

Now create a controller class and get the value from dev or test profiles.

4- Create a controller with a rest end point that return name property value for different phase.

@RestController
public class ProfileController {
	@Value("${name}")
	private String name;
	
	@GetMapping("/profile")
	public String testProfile() {
           return "Current Envirnment is "+ name;
	}
}

5- Now Run your application and hit the URL

http://localhost:8080/profile

OUTPUT:

Set active profile to dev in your application.properties file

Set active profile to test in your application.properties file

Profile in spring boot

Find Complete Code on GitHub- [ Spring Boot profile GithubUrl ]

You may also like.

Spring boot Actuator for production environment monitoring Example

How to use multiple databases with single spring boot project.

Help Others, Please Share

In this post we will see how to use log4j in java or spring boot . Logging is a most important feature that we use to detect if any error occurs or not .

Spring boot by default provides slf4j logging in spring boot. For Using slf4j logging we have to include only web starter dependency.

Logging plays a important role while we debug our application on server. using log4j in java is very important. So try to make as simple as possible so anybody can understand about the issue after seeing your logs.

In this post we will see how to use Apache Log4j in spring boot application. To use Apache Log4j we have to follow below steps.

1- Add below dependency in your pom.xml file or get this from maven Repositry to enable log4j in java
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.16</version>
</dependency>
2- create a properties file with name log4j.properties in your project resource folder and add below lines .

For Linux Server:

log4j.rootCategory=INFO, A1

log4j.appender.A1=org.apache.log4j.FileAppender

log4j.appender.A1.File=/var/log/data.log

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%d{DATE} %F|%L : %m%n

For Window Console or your Eclipse Console make below entry in your log4j.properties :

pattern=%d %5p [%24t] %32c{2}|%L - %m%n
log4j.rootLogger=DEBUG, Console, Appender1

# console is set to be a ConsoleAppender.
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=${pattern}
log4j.appender.Console.Threshold=info

# Define the file appender
log4j.appender.Appender1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Appender1.File=/var/log/R2faSupportNew.log

#log4j.appender.Appender1.File=${catalina.home}/logs/revesecure_api.log
log4j.appender.Appender1.DatePattern='.'yyyy-MM-dd

# Set the append to false, should not overwrite
log4j.appender.Appender1.Append=true

# Set the threshold to debug mode
log4j.appender.Appender1.Threshold=info

# Define the layout for file appender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout

log4j.appender.Appender1.layout.conversionPattern=${pattern}
3- Now go to your class and initialize the Logger object like below
private static final Logger logger = Logger.getLogger(CalculateSMSCost.class.getName());
4- Now go to your java class and print your logs like below.
logger.info("Apache log4j logging Example");
Now run your application and see the logs on console.

You may also like:

File Upload in Spring Boot

Spring boot security using JWT ( JSON WEB TOKENS ).

Actuator in spring boot for monitoring application

Help Others, Please Share

In this post we will see spring boot change tomcat port example. As we Know by default spring boot application on port 8080. And some time we have to change this running port if some other application is already running on 8080 port.

And we also know spring boot provides embedded tomcat server, we don’t have to install tomcat explicitly and add it to our Eclipse IDE.

It is very simple to change port of Tomcat in spring boot You juts have to go to your application.properties file and add below properties there.

server.port=8989

Here i am giving 8989 port. Now if i run my application than it will run on port 8989 and my URL will be.

http://localhost:8989

But sometimes we have to change the by default running port number if any application is running on port 8080 or the given port. So here the spring boot change tomcat port topic comes.

you can check if any application running on port 8080 in windows using following command:

1- open cmd and type below command

netstat -ano | findstr :8080

If anything running on port 8080 then you will get output like

TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       12412
TCP    [::]:8080              [::]:0                 LISTENING       12412

if you want to free the port 8080 then you have to use the below command

taskkill /PID 12412 /F

No your port 8080 is free now you can run your spring boot application on this port.

And if you are using the Linux OS then you can use the below commands.

1- To check if 8080 port is already occupied by any other application or not. Use below command in your linux console.

netstat -alnp | grep 8080

And if anything application is running on this application than you can use below command to free 8080 port.

kill -9 8539

In above command 8539 is a pid which you will get when you run the netstat command for checking port is free or not.

Now suppose there is already a application running on port 8080 and you don’t want to kill that process that is running on port 8080 and you also want to run your tomcat. so you have to change the port of your server.

for changing port go to application.properties file and add the below line

server.port=8082

Now run your Spring boot project. At this time your application is running on port 8082. So your Spring Boot project URL will be like

http://localhost:8082

You may also like:

How to use H2 database in spring boot application

How to read property values in spring boot application

Spring Boot With MySql

Spring boot cache example

Swagger2 in Spring Boot

Refrence:

Spring boot official docs.

Help Others, Please Share

As we all know MongoDB is a No SQL database, springboot provides a MongoTemplate object to perform MongoDB operations. We just have to autowired this object in our service class. In this example we will see how to perform MongoDB CRUD operations in SpringBoot with MongoTemplate.

For performing MongoDB queries operations in springboot we have to follow some steps:

1- create a springboot project and add the following dependencies in your pom.xml file.

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</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>
 </dependency>

2- After adding dependency in pom.xml file go to application.properties file and add following lines.

spring.data.mongodb.database=vasuMongoDB
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

3- create a service class and autowired the object of MongoTemplate class.

@Autowired
 private MongoTemplate template;

4- perform database crud operation using this template object .

We are creating a mongoDb crud application for user data. you can see the complete code on Github

SAVE Data:

@Override
public JSONObject save(JSONObject payload) {
        try {
            Document condition = new Document();
            String fName = payload.get(Collections.userCollection.FIRST_NAME).toString();
            String lName = payload.get(Collections.userCollection.LAST_NAME).toString();
            String email = payload.get(Collections.userCollection.EMAIl).toString();
            condition.clear();
            condition.append(Collections.userCollection.FIRST_NAME, fName)
                    .append(Collections.userCollection.LAST_NAME, lName)
                    .append(Collections.userCollection.EMAIl, email);

            
            MongoCollection<Document> collection = template.getCollection(Collections.userCollection.COLLECTION_NAME);
            collection.insertOne(condition);
            Object getInsertId = condition.get("_id");
            logger.info("vvv::  insertId= " + getInsertId);
            if (getInsertId.toString().equals("")) {
                return responses.getResponse(responses.ERROR);
            }
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find All Data:

  public Object getAll() {
        try {
            condition.clear();
            condition.append(Collections.userCollection.EMAIl, new Document("$ne", ""));
            Object findAll = find(condition, Collections.userCollection.COLLECTION_NAME);
            return findAll;
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

FindBy id:

 public Object find(Document condition, String collectionName) {
        try {
            FindIterable<Document> find = template.getCollection(collectionName).find(condition);
            MongoCursor<Document> iterator = find.iterator();
            Document docsResponse = new Document();
            JSONArray responseArr = new JSONArray();
            while (iterator.hasNext()) {
                responseArr.add((JSONObject) parser.parse(iterator.next().toJson().trim()));
            }
            if (responseArr.size() > 0) {
                return responseArr;
            }
            return null;
        } catch (Exception e) {
            logger.error(e, e);
            return null;
        }
    }

Delete Data:

      public JSONObject delete(Document condition, String collectionName) {
        try {
            Document findOneAndDeleteResponse = template.getCollection(collectionName).findOneAndDelete(condition);
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Update Data:

public JSONObject update(JSONObject whereObj, JSONObject updateObj, String collectionName) {
        try {
            logger.info("vvv::  whereObj= " + whereObj + ", updateObj= " + updateObj + ", collName= " + collectionName);
            if (whereObj == null || updateObj == null || collectionName == null) {
                logger.info("vvv::  insufficentData");
                return responses.getResponse(responses.INSUFFICIENT_DATA);
            }
            Query query = new Query();
            Update update = new Update();

            //iterate where Condition
            Set keySet = whereObj.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                query.addCriteria(Criteria.where(key).is(whereObj.get(key)));
            }

            //iterate Update Value
            Set updateSet = updateObj.keySet();
            Iterator updateItr = updateSet.iterator();
            while (updateItr.hasNext()) {
                String key = (String) updateItr.next();
                update.set(key, updateObj.get(key));
            }
            logger.info("vvv::  query= " + query.toString());
            logger.info("vvv::  update= " + update.toString());
            UpdateResult updateMulti = template.updateMulti(query, update, collectionName);
            logger.info("vvv::  updateMulti= " + updateMulti);
            if (updateMulti.getModifiedCount() == 1) {
                return responses.getResponse(responses.OK);
            }
            return responses.getResponse(responses.ERROR);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find Complete Code on Github

https://github.com/vasurajput/JavaDream/tree/master/SpringBootMongoDB
Help Others, Please Share

AngularJs has widely used technology nowadays which is introduced by GOOGLE and it is mainly used for single page application. To integrate AngularJs with SpringBoot is very simple we can integrate AngularJs with CDN also but in this, I will show you how to integrate AngularJS using webjars in spring boot. We have to follow some steps to integrate AngularJS with SpringBoot and Steps are:

Steps to follow:

  1. Add AngularJs webJar in your pom.xml file
  2. create a javascript file inside your static folder
  3. link webjar and javascript file in your JSP page
  4. Create a Controller class for display your JSP page

Project Directory Structure:

1- Angular WebJar :

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

2- main.js

var app=angular.module('myapp',[]);
app.controller('myctrl',function($scope){
$scope.firstname="vasu Rajput";
});

3- index.jsp

<html ng-app="myapp">
<body ng-controller="myctrl">
    <h1>Hi You are a Nice Guy {{firstname}}</h1>
    <p>Angular Example 2 way Binding</p>
    <input type="text" ng-model="tyeMe"><br>
    <h4>{{tyeMe}}</h4>
    <script src="webjars/angularjs/1.7.0/angular.js"></script>
    <script src="JS/main.js"></script>
</body>
</html>

4- MyController.java

@Controller
public class MyController {
@GetMapping("/")
public String index() {
return "index";
}
}

Now run your programe you will see output like:

Help Others, Please Share

Sending email is a very basic task in every applications. Spring boot provides JavaMailSender interface that is used for sending Simple text as well as HTML email to end user. So for sending email in spring boot we have to follow some steps and steps are:

  1. Create a spring boot projects using spring initializer with Mail dependency.
  2. Write your email properties in application.properties file.
  3. Create a Controller class and make a POST end point to receive email id.
  4. Create a Service class for sending email to given email id.
  5. we will send both simple text as well as HTML email to given email id.

Project Directory Strucuture

2- Write your email properties in application.properties file.

 spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=vasu@gmail.com
spring.mail.password= Write Your Gmail Account Password
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000

3- Create a Controller class and make a POST end point to receive email id

 @RestController
public class MyController {

@Autowired
private MyService service;

@PostMapping("/sendMail")
public ResponseEntity sendEmail(@RequestParam String emailId) {

ResponseEntity sendResult = service.send(emailId);
return sendResult;
}
}

4- Create a Service class for sending email to given email id.

First We Send a Simple plain Text Message to given Email Id

 @Service
public class MyService {

@Autowired
JavaMailSender mailSender;

public ResponseEntity<?> send(String emailId) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
messageHelper.setTo(emailId);
messageHelper.setSubject("Testing");
messageHelper.setText("Nice Try");
mailSender.send(message);
System.out.println("succesfully SendEmail");
return new ResponseEntity<Object>("succesfully SendEmail",HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<Object>("Error in sending Mail", HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Now Send a HTML message to given email id. For sending HTML email just write your message in HTML formate and set setText boolean flag to true


Eg:
StringBuilder builder = new StringBuilder();
builder.append("<html><h3>Email in HTML</h3></html>");
messageHelper.setText(builder.toString(), true);

@Service
public class MyService {
@Autowired
JavaMailSender mailSender;

public ResponseEntity<?> send(String emailId) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
StringBuilder builder = new StringBuilder();
builder.append("<html><h3>Email in HTML</h3></html>");
messageHelper.setTo(emailId);
messageHelper.setSubject("Testing");
messageHelper.setText(builder.toString(), true);
mailSender.send(message);
System.out.println("succesfully SendEmail");
return new ResponseEntity<Object>("succesfully SendEmail", HttpStatus.OK);
}catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<Object>("Error in sending Mail", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}




Help Others, Please Share

Configure your application with database is the basic need of every project. Spring Boot provides JPA (java Persistance API) to Connect to MySQL database. For connecting our Spring Boot application we have to follow some basic steps, and steps are:

  1. Create a Spring Boot Project with MySQL and JPA dependency
  2. Configure MySql properties in application.properties file
  3. create a Model Class
  4. Create a interface repository that extends JpaRepository interface
  5. Create a Controller Class
  6. Create a Service Class for business logic.
  7. Create a Response Class For Display Custom Responses.

2- Configure MySql properties in application.properties file

 spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/vasu
spring.datasource.username=root
spring.datasource.password=12345@
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
hibernate.hbm2ddl.auto=create-drop
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardI mpl

3- Create a Model Class, We are creating a Model Class With Name Student

 @Entity
@Table(name = "Student")
public class StudentModel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id", nullable = false)
private Long id;

@Column(name = "Name", nullable = false)
private String name;

@Column(name = "Age", nullable = false)
private int age;

@Column(name = "Email", nullable = false, unique = true)
private String email;

//Constructor
//Getter-Setter

4- Create a interface repository that extends JpaRepository interface

 @Repository
public interface StudentRepositry extends JpaRepository {
}

5- Create a Controller Class

 @RestController
public class StudentController {

@Autowired
private StudentService service;

@GetMapping("/")
public ResponseEntity getAll() {
ResponseEntity get = service.get();
return get;
}

@GetMapping("/getById/{id}")
public ResponseEntity getById(@PathVariable("id") Long Id) {
ResponseEntity byId = service.getById(Id);
return byId;
}

@PostMapping("/update")
public ResponseEntity update(@RequestParam Long id,
@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {
ResponseEntity update = service.update(id, new StudentModel(name, age, email));
return update;
}

@GetMapping("/delete/{id}")
public ResponseEntity delete(@PathVariable("id") Long id) {
ResponseEntity delete = service.delete(id);
return delete;
}

@PostMapping("/insert")
public ResponseEntity insert(@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {

ResponseEntity save = service.save(new StudentModel(name, age, email));
return save;
}

6- Create a Service Class for business logic

@Service
public class StudentService {
private static final Logger logger = LoggerFactory.getLogger(StudentService.class.getName());

@Autowired
private StudentRepositry dao;
@Autowired
private Responses response;

public ResponseEntity save(StudentModel student) {
try {
StudentModel save = dao.save(student);
return new ResponseEntity(save, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity get() {
try {
List findAll = dao.findAll();
return new ResponseEntity(findAll, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

public ResponseEntity update(Long id, StudentModel student) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
get.setAge(student.getAge());
get.setEmail(student.getEmail());
get.setName(student.getName());
StudentModel save = dao.save(get);
return new ResponseEntity(save, HttpStatus.OK);
}
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity delete(Long id) {
try {
dao.deleteById(id);
return new ResponseEntity(response.getResponse(response.OK), HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity getById(Long id) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
return new ResponseEntity<Object>(get, HttpStatus.OK); }
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

7- Create a Response Class For Display Custom Responses.

/*
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.
*/

@Component
public class Responses {
private static final Logger logger = LoggerFactory.getLogger(Responses.class.getName());

public static final int OK = 0;
public static final int ERROR = 1;
public static final int INSUFFICIENT_DATA = 3;
public static final int INVALID_USER = 4;
public static final int UNKNOWN = 501;

public static JSONObject getResponse(int code) {
logger.info("vvv:: responseCode= " + code);
JSONObject response = new JSONObject();
switch (code) {
case OK:
response.put("code", OK);
response.put("message", "OK");
break;
case ERROR:
response.put("code", ERROR);
response.put("message", "Internal Error");
break;
case INSUFFICIENT_DATA:
response.put("code", INSUFFICIENT_DATA);
response.put("message", "Insufficient Data");
break;
case INVALID_USER:
response.put("code", INVALID_USER);
response.put("message", "Invalid User");
break;
default:
response.put("code", UNKNOWN);
response.put("message", "Unknown Response code");
}
logger.info("vvv:: MakeResponse= " + response); return response;
}
}

OUTPUT

Help Others, Please Share

We know that when we create a Spring Boot project it will make a JAR file after compilation. But some developers prefers WAR over JAR for deploying their application on tomcat server. so for converting JAR into WAR in Spring Boot application we have to follow some rules and the rules are:

  1. Add spring-boot-starter-tomcat dependency into pom.xml file.
  2. change packaging to war instead of jar in pom.xml file.
  3. Go to your Spring Boot main class and extends SpringBootServletInitializer abstract class.
  4. Override the SpringApplicationBuilder method of
    SpringBootServletInitializer abstract class .
  5. Now just clean and build your project you will get your war file inside target folder of your project.

1- Add below dependency to pom.xml

<dependency> 
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

2- Change packaging to war instead of jar in pom.xml file

<packaging>war</packaging> 

3- Go to main class and extends SpringBootServletInitializer abstract class.

@SpringBootApplication
public class SpringBootWarExampleApplication extends SpringBootServletInitializer{

4- Override the SpringApplicationBuilder method of
SpringBootServletInitializer abstract class

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder app) {
return app.sources(SpringBootWarExampleApplication.class);
}

Now Your Main Class will look like this

package com.vasu.SpringBootWarExample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootWarExampleApplication extends SpringBootServletInitializer{

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder app) {
return app.sources(SpringBootWarExampleApplication.class);
}

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

5- Now just clean and build your project you will get your war file inside target folder of your project.

You may also like

Change Default Banner Spring Boot

How to read property values in spring boot application

How to use H2 database in spring boot application

Spring Boot With MySql

Profiles in Spring boot application

spring batch example

Help Others, Please Share

x