Best ways to run spring boot app via command line

We can easily build spring boot application using mvn spring-boot:run and run spring boot app via command line . Assuming you have already created a simple spring boot app, here are the next steps you need to follow to run spring boot app .

Add Maven Plugin in Your Spring Boot Project

In order to run your spring boot app , we need to add spring-boot-maven-plugin in your project parent pom.xml. Open your project pom.xml and add the following line inside it . In most of the cases it will be present already .


Running Spring boot apps as Jar from Command line

In order to run your spring boot app as jar we need to first build our application . Navigate to your project folder and run the following command to build your app.

mvn clean install 

Now that your project is build successfully , navigate to target directory and locate your spring boot app jar . You jar file name would be something like webapp-1.0.0SNAPSHOT.jar where webapp is the artifactid . Now issue the following command

java -jar webapp-1.0.0.SNAPSHOT.jar 

Running Spring boot based app with profiling enabled

We can also do profiling in our spring boot based app and run the jar in linux . Have a look at How We can enable Profiling in spring boot app.

java -jar -Dspring.profiles.active=dev webapp-1.0.0.SNAPSHOT.jar 

We can also set server port in spring boot app from command line using following command

java -jar -Dspring.profiles.active=dev -Dserver.port=9090 webapp-1.0.0.SNAPSHOT.jar  

Running Spring boot app via command line using maven

Now , I personally really love this command here , reason is it proved to me as Mr Dependable for me . I was getting a some weired issue like my tomcat used to stop without showing any error . I used to use this command and it used to show me the exact error in debug mode .

I was basically having issue in autowiring and i disabled my debug mode by mistake . I found that this actually runs in debug mode for me .

mvn spring-boot:run

This command line run will also be beneficial when you’re using spring-boot-dev-tool with auto reload/restart when you have changed you application.


How to Run spring Boot App Using Gradle

If you are using gradle as your build tool to build spring boot app , you can try following code to run spring boot app using gradle

./gradle bootRun

How to provide hot fix in spring boot apps

lets take an example where we want to provide hot-fix in spring boot apps . Let’s say we missed a logic in one of our classes and now we have fixed , but deployment and build takes time .

In those scenarios if you have a spring boot app packaged as jar . We need to follow these steps .

  1. Extract the Jar using following command
Jar -xvf webapp-1.0.0.SNAPSHOT.jar

2.Once you extract the jar you will find following structure

spring boot extract jar

Now , you can update your hotfix class file directly , most of the compiled classes are present inside BOOT-INF/classess including your application.properties.

Now you can run following command in spring boot to run this extracted spring boot jar .

java -Dspring.profiles.active=dev -Xdebug -Xnoagent -Djava.compiler=NONE org.springframework.boot.loader.JarLauncher 

Notice we mention profiles as well, if you are not sure . Learn how can you profile your spring boot apps.

These were the top best ways you can run spring boot app from command line .

Have a look at other tutorials on Spring :-

Configure SSL Spring Boot 2

Learn Spring Security

How to Configure SSL In Spring Boot 2

SSL Configuration Spring Boot 2.0

How to Configure SSL In Spring Boot 2:-

In this post, we are going to learn How to Configure SSL in Spring Boot 2. There are two different ways to configure SSL in Spring Boot 2.

  1. Using Default Configurations.
  2. Using Custom Configurations.

One of the prerequisites to Configure SSL is to have an SSL Certificate.

We can generate an SSL certificate ourselves known as a self-signed certificate for the development. 

In production, you should use a certificate issued by a trusted Certificate Authority (CA). It gives you a certificate file basically which we need to use in our code.

We will see how we can use the Self Signed Certificate file to Configure SSL In Spring Boot 2.

Tools and Technologies Used:-

  • Java JDK 8 (1.8.0_152)
  • Spring Boot 2.0.4.RELEASE
  • Maven 3.5

Using Basic Configurations to Setup SSL In Spring Boot 2:-

Spring Boot provides a way to configure SSL . We can mention few properties in our application and we are good to go.

Let’s Check a few of the properties below.


As you can see in above properties we have used JKS keystore file type and given the name as keystore.jks This is the Self Signed Certificate has been generated and its copied under src/main/resources folder in spring boot.

While generating the Self Signed Certificate it asks for the password and we set alias which we have added in our properties.

As 8080 is considered to be a non-SSL port, We have configured the server port as 8443, to follow a standard.

Now Create a rest Service and run your application, you will be able to access the application using HTTPS. This is the simplest way to configure  SSL in any Spring Boot applications. Let’s have a look at the advanced level of configurations

Using Custom Configurations to Setup SSL in Spring Boot 2:-

Lets have a look at what we want here . We want our Keystore password to be encrypted in properties file using our own custom encryptor .

For the above requirement we need to Customize the Spring Boot SSL configurations.In Order to customize Spring Boot SSL configurations we need to Implement WebServerFactoryCustomizer

Any bean implementing this interface will get a callback with the server factory before the server itself is started . We can customize the Port ,Address,Password of the embedded Server.

package com.frugalis.ssl.App;

import java.io.File;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import com.frugalis.common.PasswordDecryptor;

public class CustomServletContainer implements
		WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    private PasswordDecryptor passwordDecrypt;

	private String keystoreFile;
	private String keystoreAlias;
	private String keystoreType;
	private String keystorePass;
        private int tlsPort;

	public void customize(TomcatServletWebServerFactory factory) {

		factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {

		public void customize(Connector connector) {
                connector.setAttribute("keyAlias", "tomcat");
                connector.setAttribute("keystorePass", "password");

                File file = new File(keystoreFile);
                String absoluteKeystoreFile = file.getAbsolutePath();
                connector.setAttribute("keystoreFile", absoluteKeystoreFile);
                connector.setAttribute("clientAuth", "false");
                connector.setAttribute("sslProtocol", "TLS");
                connector.setAttribute("SSLEnabled", true);

                Http11NioProtocol proto = (Http11NioProtocol) connector.getProtocolHandler();


    public void ProcessPassword() {
          keystorePass = passwordDecrypt.decryptPassword(keystorePass);

We have Configured Profiling to enable SSL in production mode in Spring Boot 2 .

Note:- In  a typical commercial  production environment we basically don’t enable SSL in application level instead its preferred to enable in the VIP level . Let me know if you guys face any issues.

Load a File From Classpath In Spring Boot

How to Load a File From Class path Spring Boot

Load a File From Classpath In Spring Boot

In this post, we are going to check How to Load a File From Classpath In Spring Boot. Long back I was working on a very simple project.

We realized Reading a property source in Spring boot is easy and it can get tricky as well .

As Spring works on the concept of fat jar it is  good to know for developer the best ways to load a file from classpath  in spring boot .

In this post, we’ll see various ways to access and load the contents of a file that’s on the classpath using Spring.

I wanted to read a JSON file from the resources folder.src/main/resources Hence written a code something like this below.

	private Resource resource;

        File file = resource.getFile();

Now, this code works completely fine once I run it using,mvn:spring-boot:run but as soon I’m building and packaging the application using maven and running it as simple executable jar I’m getting an exception. Let’s go ahead and find out the solution now.

Using InputStream  

We can use InputStream to read a file from classpath in your Spring boot application . Let’s define the name of json file to be read with Resource .

	Resource resourceFile;

Let’s See How We can read the File , We will now show you actual code to Write and retrieve the content of file from your spring boot based application.

    private void testResource(Resource resource) {
		try {
			InputStream resourcee = resource.getInputStream();
			String text = null;
			try (final Reader reader = new InputStreamReader(resourcee)) {
				text = CharStreams.toString(reader);

		} catch (IOException e) {

We have seen How we can Load a File From Classpath In Spring Boot If the file is inside a jar.

Reading as a File:-

There is another way to load resources in spring boot. We are now going to check how we can load a file from classpath in spring boot if the file is present in the filesystem not inside a jar.

	public void testResourceFile() throws IOException {
		File resource = new ClassPathResource("test.json").getFile();
		String text = new String(Files.readAllBytes(resource.toPath()));

Reading Resource as ResourceLoader:-

ResourceLoader is used to loads resources from class-path as well as file system. It is one of the very commonly used way to read a file from classpath .

ResourceLoader resourceLoader;
Resource resource=resourceLoader.getResource("classpath:test.json");

Now we can use resource.getInputStream() or resource.getFile() as required.

Using ResourceUtils:-

Load a file from classpath in spring boot using ResourceUtils resolves the given resource location to a,java.io.File i.e. to a file in the file system.It doesn’t check if the file exists or not.

It is my most preferred way of doing it in any spring boot based application i am working .


Note:-   Visit this Site to Understand More about Basics Of Java and Collections.

Configure Swagger With Jersey and Spring Boot

Swagger Jersey Integration Example

Configure Swagger With Jersey and Spring Boot

We are going to configure Swagger With Jersey and Spring Boot. We saw applications are moving towards micro-services architecture. one of the important aspects of API development is API documentation. Great documentation results in proper experience in API consumption. We are going to use and Configure Swagger and Swagger UI for API documentation along with Jersey and Spring Boot.

Swagger is Used for standardizing API documentation and provide a consistent specification. Swagger UI  helps in visualizing and interact with our API’s.

Integration of Spring with Swagger is a straightforward task with  Spring provided annotations. Using Spring Boot Swagger with JAX-RS is a bit tricky task. Let’s continue and create a  Spring Boot Jersey Project referring our post Spring Boot Jersey Example.

Project Dependencies:-

  1. Spring Boot
  2. swagger-jersey2-jaxrs
  3. spring-boot-starter-web

Here is our pom.xml with spring boot swagger maven dependency and other required dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


	<description>Demo project for Spring Boot</description>

		<relativePath /> <!-- lookup parent from repository -->








Configuration Of Swagger and Jersey:-

Now we have already added swagger maven dependencies, now it’s the time to configure swagger with jersey and spring boot. Lets  add a swagger configuration in our Jersey Config as below.

package com.frugalis.SpringBootJersey;

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;

import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JerseyConfig extends ResourceConfig {

	public JerseyConfig(ObjectMapper objectMapper) {
		register(new ObjectMapperContextResolver(objectMapper));

	public static class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
		private final ObjectMapper mapper;
		public ObjectMapperContextResolver(ObjectMapper mapper) {
			this.mapper = mapper;

		public ObjectMapper getContext(Class<?> type) {
			return mapper;
	  public void init() {
	    // Register components where DI is needed
	private void SwaggerConfig() {
	    BeanConfig swaggerConfigBean = new BeanConfig();
	    swaggerConfigBean.setConfigId("Frugalis Swagger Jersey Example");
	    swaggerConfigBean.setTitle("Using Swagger ,Jersey And Spring Boot ");
	    swaggerConfigBean.setSchemes(new String[] { "http", "https" });

We are setting basepath asswaggerConfigBean.setBasePath("/api") this path could be anything. On successful setup, we can check our swagger setup is working or not by going to http://localhost:8080/api/swagger.json

Once we get an output JSON as response, our first step to Configure Swagger With Jersey and Spring Boot is Done.

Now the next step is Configuring Swagger UI.

Configure and Setup Swagger UI:-

Visit Swagger UI GitHub project and download dist version of the Project. Extract contents and move the dist content to /src/main/resources/static , we can create the folder structure if it is not present. The dist folder under the GitHub project contains  JavaScript, CSS, images and HTML files used for swagger UI.

We need to update index.htmlinside forsrc/main/resources/static/index.html Swagger UI to find the configuration and load the UI accordingly. Replace text withhttp://petstore.swagger.io/v2/swagger.json to your  swagger.json URL. In this case, our swagger.json is located at http://localhost:8080/api/swagger.json

    window.onload = function() {

      // Build a system
      const ui = SwaggerUIBundle({
        url: "api/swagger.json",
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
        plugins: [
        layout: "StandaloneLayout"

      window.ui = ui


configure swagger with jersey and spring boot
[sociallocker id=”1183″]



Deploy Spring Boot App On Heroku

Deploy Spring Boot App On Heroku:-

Heroku is a platform as a service (PaaS) that developers use to deploy, manage and run apps on the cloud. There are a wide range of programming languages supported on Heroku platform.

In this article, you are going to see How to deploy Spring Boot app on Heroku with step by step guide. There are different ways to Deploy Spring boot app on Heroku and we are going to see a couple of convenient ways.

Project Structure Of Spring Boot App:-

Let’s go ahead and create a simple app using spring initializr. Please follow the steps to create a simple spring boot app.

  1. Enter Group name as com.frugalis
  2. Enter artifact id as SpringHeroku.
  3. Click on Generate and import in your favorite IDE.

Now let’s go ahead and write a simple controller as below, we are now ready with a simple app to deploy spring boot app on Heroku. Please have a look at one of our blog post to Create Rest Services Using Spring Boot.

1.Deploy Spring Boot App On Heroku Using Heroku-CLI:-

First of all, you need to login to Heroku account. If you don’t have one, you can create it from Heroku’s Signup Page.We are going to use Heroku CLI and Git. Let’s follow the steps now to deploy.

1.1 Download And Install Heroku CLI:-

Heroku CLI is a command line tool that helps to manage Heroku apps using the terminal. Please Download Heroku CLI and follow the instructions to install it on your computer.

 1.2 Create Heroku App:-

Navigate to your Heroku dashboard by using the Dashboard link. Click on New button on right most corner and click on Create New App button.

Heroku Dashboard

You will get something like this below,

Spring Boot App On Heroku

Please enter the app name and click on create an app. Please note down the app name you entered. It will take you to Heroku app and the app page looks like below.

Spring Boot Heroku Deploy

1.3 Login to Heroku CLI:-

If you haven’t already, log in to your Heroku account.P lease open command prompt/terminal and enter the following command.

$ heroku login

You will be prompted to enter your Heroku account’s credentials.

Enter your Heroku credentials:
Email: xyz@abcd.com
Password: *********
Logged in as xyz@abcd.com

1.4 Deploy Spring Boot App On Heroku using Heroku Git:-

Please navigate to your Spring Boot project and execute the following list of commands sequentially.

Deploy Spring Boot On Heroku

We have now deployed our app on Heroku. Here frugalisapp  is the app name. You can get these commands in  app page under deploy section. You can open deployed app using Herok by executing the command .

$ heroku open

2. Deploy Spring Boot App Using Jar File:-

Before going on to the details, Let’s look at few of the important plugins and install those . We are going to deal with two plugins Heroku Repo and Heroku CLI Deploy respectively.

Let’s clean the cache and reset the app using Heroku repo.

$ heroku plugins:install heroku-repo
$ heroku repo:gc -a appname
$ heroku repo:reset -a appname

Now let’s deploy our Spring Boot project using Heroku CLI Deploy plugin.

Open application.properties from src/main/java/resources/application.properties.

Please add following line below.


Navigate to Spring project folder and run.

$mvn clean package

Now run deploy command from your project directory.

$ heroku deploy:jar target/SpringHeroku-0.0.1-SNAPSHOT.jar --app <APP-NAME>

3Deploy Spring Boot App On Heroku Using Procfile:-

We are going to add a Procfile in our spring boot app like below

web: java -Dserver.port=$PORT $JAVA_OPTS -jar target/*.jar

Now execute the deploy plugin again as below:-

$ heroku deploy:jar target/SpringHeroku-0.0.1-SNAPSHOT.jar --app <APP-NAME>

Drop us an Email With Subject “Help On Spring Boot heroku ” if you want our team to help you on deploying any Spring boot App on heroku !! Free !!!!!! 

[sociallocker id=”1183″]

Download Code

Related Links:-

CRUD Rest API With Spring Web-Flux Reactive Programming with Spring 5

Creating REST Service with Spring Boot

CRUD Rest Service With Spring Boot and JPA

Spring Boot Profiling – Configure for Different Environments

Spring Boot File Upload and Download Example with Rest API

Spring Boot file upload

Most of the times file upload task are not simple as it looks like in any language . If you want to do in Java world with spring boot file upload and download .

In this example, we are going to check how to Upload File Using Spring Boot and REST. We are going to use Spring MultipartFile  to upload our  files using Spring Boot using  REST API . Multipart is one of the most efficient way to handle large file uploads in spring . Spring boot multiple file uploads are easily handled by spring MultipartFile in java .

We are also going to check How to download files with Spring Boot and  spring boot rest services.

Technologies Used:-

  • Spring Boot 2.0
  • Maven 3.0
  • Java 1.8

Project Structure:-

Spring Boot Rest File Upload

Create File Upload Controller:-

We are going to upload a single file and upload it using  MultipartFile .

Let’s configure our Spring Boot application to enable Multipart file uploads and return the name of the uploaded file. Let’s write a request mapping and write a basic REST Controller. This is a sample controller and we will be writing logic later in the section.

package com.frugalis.SpringRestFileUpload;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Random;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadController {

	String UPLOAD_DIR = "D://upload//";
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(@RequestParam(value = "file") MultipartFile file) throws IOException {
	@RequestMapping(value = "/upload/{galleryId}", method = RequestMethod.GET)
	public ResponseEntity<byte[]> getFile(@PathVariable("galleryId")String galleryId) throws IOException {
	private String getRandomString() {
		return new Random().nextInt(999999) + "_" + System.currentTimeMillis();

	private File getTargetFile(String fileExtn, String fileName) {
		File targetFile = new File(UPLOAD_DIR + fileName + fileExtn);
		return targetFile;

	private String getFileExtension(MultipartFile inFile) {
		String fileExtention = inFile.getOriginalFilename().substring(inFile.getOriginalFilename().lastIndexOf('.'));
		return fileExtention;


We are configuring endpoints as /upload and /upload/{imageId} . We written methods to return random string as well as the file format as we are going to need those while saving file.

Create REST API for uploading files in Spring Boot 

@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(@RequestParam(value = "file") MultipartFile file) throws IOException {

		String fileExtension = getFileExtension(file);
		String filename = getRandomString();

		File targetFile = getTargetFile(fileExtension, filename);

		byte[] bytes = file.getBytes();
		String UploadedDirectory = targetFile.getAbsolutePath();

		return filename;

getTargetFile()creates a file object using UPLOAD_DIR, filename, and file extension.We are using MultipartFile.getBytes()to save the target file and return target file path in response.

Testing Code:-

Upload File using Spring Boot and REST

Download Code