Spring Boot Getting Started using Maven and Gradle with Eclipse

@SpringBootApplication

@Configuration

@EnableAutoConfiguration

@ComponentScan

SpringApplication.run()

@SpringBootTest

Step 1: Software Used in the Demo Application

Step 2: Start Creating Project using Spring Initializer

Step 3: Configure Eclipse Classpath

Step 4: Create Application

package com.concretepage; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

package com.concretepage.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.concretepage.domain.Employee; import com.concretepage.service.EmployeeService; @RestController public class EmployeeController { @Autowired private EmployeeService service; @RequestMapping("home") public List<Employee> showData() { List<Employee> list = service.getAllEmployee(); return list; } }

package com.concretepage.domain; public class Employee { private int id; private String name; private String location; public Employee(int id, String name, String location) { this.id = id; this.name = name; this.location = location; } public int getId() { return id; } public String getName() { return name; } public String getLocation() { return location; } }

package com.concretepage.service; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; import com.concretepage.domain.Employee; @Service public class EmployeeService { public List<Employee> getAllEmployee() { List<Employee> list = new ArrayList<>(); list.add(new Employee(1, "Mahesh", "Varanasi")); list.add(new Employee(2, "Ram", "Ayodhya")); list.add(new Employee(3, "Krishna", "Mathura")); return list; } }

Step 5: Run Application using Maven

<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.concretepage</groupId> <artifactId>spring-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

[{"id":1,"name":"Mahesh","location":"Varanasi"},{"id":2,"name":"Ram","location":"Ayodhya"},{"id":3,"name":"Krishna","location":"Mathura"}]

Step 6: Run Application using Gradle

plugins { id 'org.springframework.boot' version '1.4.3.RELEASE' id 'java' id 'eclipse' } archivesBaseName = 'spring-demo' version = '0.0.1-SNAPSHOT' repositories { jcenter() } dependencies { compile("org.springframework.boot:spring-boot-starter-web") }

Understanding Maven for Spring Boot

pom.xml

pom.xml

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> <relativePath/> </parent>

pom.xml

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

pom.xml

<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>

Understanding Gradle for Spring Boot

build.gradle

build.gradle

compile('org.springframework.boot:spring-boot-starter-web')

id 'org.springframework.boot' version '1.4.3.RELEASE'

Using @EnableAutoConfiguration Annotation and SpringApplication Class with Main method

@EnableAutoConfiguration

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

SpringApplication.run()

. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.4.3.RELEASE) 2017-01-11 18:27:52.323 INFO 2208 --- [ main] com.concretepage.MyApplication : Starting MyApplication on Renu-PC with PID 2208 (F:\arvind\PROJECT\mars\spring-boot\spring-demo\build\classes\main started by Renu in F:\arvind\PROJECT\mars\spring-boot\spring-demo) 2017-01-11 18:27:52.328 INFO 2208 --- [ main] com.concretepage.MyApplication: No active profile set, falling back to default profiles: default

Using @SpringBootApplication Annotation

@Configuration

@ComponentScan

@EnableAutoConfiguration

src/main/java - | -- MyApplication.java -- controller -- domain -- service

@SpringBootApplication

@Configuration

@EnableAutoConfiguration

@ComponentScan

MyApplication.java

@SpringBootApplication

package com.concretepage; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

@Configuration

@EnableAutoConfiguration

@ComponentScan

package com.concretepage; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

Useful Commands for Spring Boot Application

.classpath

.classpath

java -jar <JAR-NAME>

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar <JAR-NAME>

Some Spring Boot Application Starters

Reference

Download Source Code

This page will walk through Spring boot getting started using maven and gradle with eclipse. Using Spring boot we can create standalone and production grade spring applications and that will be ready to run. Many spring configurations and JAR dependencies are auto configured. We can start our application usingas well as deploying WAR file. Spring boot applications have following features.1. Spring boot performs many configurations automatically. So the development is faster.2. Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers with default port 8080.3. Using spring boot we can externalize our configurations so that we can work with the same application code in different environments. We can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.4. Spring Boot uses Commons Logging for all internal logging, but we can also implement our Logging. By default Logback is used.5. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr and Cassandra NoSQL technologies.6. Spring boot auto configures the necessary infrastructure to send and receive messages using JMS.7. Spring boot providesthat allows spring boot to configure spring application based on JAR dependencies that we have added.8. Spring providesannotation that is the combination ofandannotations.9. Spring boot usesinside java main method to bootstrap the application.10. Spring Boot provides aannotation to test spring boot application.Here on this page we will craete Spring REST application from scratch using spring boot step by step.We are using following software to run our application.1. Java 8 (Minimum Required Java 7)2. Maven 3.3.93. Gradle 3.34. Spring Boot 1.4.3.RELEASE5. Eclipse MarsWe need to make sure that these software are installed in the system.Go to the spring initializer URLand here we will select following details.a. First select Maven project or Gradle project. For the example we have selected maven project.b. Now select the spring boot version. In our example we have selected spring boot version asc. We need to specify artifact coordinates i.e. group and artifact name. In our example I have specified project metadata as following.Group: com.concretepageArtifact: spring-demod. Now select dependencies required by project. If we want to create web project then enterkeyword and we will get drop-down for web and select it. This will provide all required JAR dependencies to develop web project.e. Now click onbutton. A project will get started to download.Find the print screen.After click onan archive file will be downloaded named as. Extract the archive fileand import the project into eclipse.First of all we will update eclipse classpath to configure required spring JAR as follows.a. Using command prompt, go to the root directory of the project.b. Run the commandThe above command will clean the existing classpath and configure all required JAR dependencies for our web project. If we select Gradle in spring initializer then we need to run following command to configure classpath.Now the time is to start coding and creating our application. In our example we are creating a simple web application. We will create a simple REST project. The application will respond JSON format values of a list. Find the project structure.We are creating following classes.Keep this main class in the parent package.Now we will run our example using maven. Find the maven file. This file will be located in the root folder of project.In exploded form we can run our application as follows.a. Using command prompt, go to the root directory of the project.b. Run the commandThe above command will start an embedded tomcat server by spring boot.Using IDE we can also run our application.1. Go to the main class2. Right click andNow access the URL using browser.We will get following output.To run the application with archive file, we will do as follows.a. Using command prompt, go to the root directory of the project.b. Run the commandThe above command will create two JAR files inside a directory named asas follows.1. Executable JAR i.e spring-demo-0.0.1-SNAPSHOT.jar2. Original JAR i.e spring-demo-0.0.1-SNAPSHOT.jar.originalRun first JAR that is spring-demo-0.0.1-SNAPSHOT.jar as follows.The above command will execute JAR that will start embedded tomcat server. Now run the URL to access the application.Now we will use gradle in our application. While creating project structure from spring initializerwe will selectand rest will be the same as using maven project. Click onbutton and a zip file will be downloaded. Import the project into eclipse and create your application. Now set eclipse classpath using following command.We can change gradle file as per our requirement. We are using following gradle file in our application. This file will be located in the root folder of project.Let us run our example using gradle. In exploded form we can run our application as follows.a. Using command prompt, go to the root directory of the project.b. Run the commandThe above command will start an embedded tomcat server by spring boot. Now access the URL using browser.To run the application with archive file, we will do as follows.a. Using command prompt, go to the root directory of the project.b. Run the commandThe above command will create two JAR files inside a directory named asas follows.1. Executable JAR i.e spring-demo-0.0.1-SNAPSHOT.jar2. Original JAR i.e spring-demo-0.0.1-SNAPSHOT.jar.originalRun first JAR that is spring-demo-0.0.1-SNAPSHOT.jar as follows.The above command will execute JAR that will start embedded tomcat server. Now run the URL to access the application.Here we will understand our. Spring provides many boot starters for different purposes. When we create a spring application then we have to configure all related JAR with proper versions. Sometimes these tasks are tedious. Here comes the role of spring boot starter. If we want to create web application then we can simply use spring boot starter for web and that will configure all related JAR. Let us understand spring boot starter management.Spring boot providesthat resolve the required JAR dependencies. One of which is. Now look into the. In parent section we have used following code snippet.is a special spring boot starter that has following features.1.provides. It keeps the list of dependencies it supports. When usingwith a base version then other spring boot starters configured in pom.xml need not to specify versions. If version specified then the default will be overridden.2.provides useful maven defaults. Using commandWe get the tree representation of project dependencies. Suppose we have configured other spring boot starters also and now we want to know all JAR dependencies used by the project then we can run the commandand it will print all JAR names used by the project.As we have created web application, so we have added spring boot starter for web. Find the code snippet fromresolves JAR dependencies for spring web application. We need not to provide itsbecause it will be handled by theversion. Spring boot starter parent will pick the correct version of all JAR provided by all configured spring boot. Usingcommand we can print all the JAR resolved byin our application and other spring boot starter if we have configured. When we usein our, spring automatically understands that we are creating spring web application and accordingly spring boot configures the required JAR.Spring boot providesthat is used to create executable JAR of the application. We will configure it as follows.Above plugin enables following maven command functionality.1.: Creates executable and original JAR both.2.: Starts the tomcat server to run application in exploded form.Now we will discuss gradle used in our web application. Look into thefile. There is no spring boot starter parent. We are directly using spring boot starter web. Let us understandstep by step.There is no spring boot starter parent in gradle. But we can use command to get dependency tree.The above command gives the list of direct and transitive dependencies.As per application requirement, we configure spring boot starter. We have created a web application, so we need to configure. We have configured it as follows.In our gradle file, for all spring boot starter version we can configure version at one place withinas follows.is available in gradle. We need not to configure it separately. Like maven, we can create executable JAR using gradle.provides the following command functionality.1.: Create executable and original JAR.2.: Starts the tomcat server to run application in exploded form.To run spring boot application we need to create a class with main method and annotated withas follows.: The task of this annotation is that it allows spring boot to configure spring application based on JAR dependencies that we have added. In our application we are usingthat will add tomcat and spring MVC JAR to our application. Sounderstands that user wants to create web application and hence it sets up spring accordingly.: It bootstraps a spring application by callingWhen we run main method we will get logs as follows.In developing spring web application, we need to use spring annotations such asand. Mostly we use these annotations withannotation at main class while creating boot application. In this case Main class should be located at the parent package as follows.Spring providesannotation that is the combination ofandannotations. So we can usein following manner.1. Using2. Usingandannotations.Here we are consolidating the commands used by the spring boot application.1. For Maven: Prints tree of JAR dependencies.: Creates: Creates JAR/WAR for the application.: Starts tomcat to run application in exploded form.2. For Gradle: Prints list of direct and transitive dependencies.: Creates: Creates JAR/WAR for the application.: Starts tomcat to run application in exploded form.3. For JavaRun Executable JAR.Run a packaged application with remote debugging support enabled.Find some frequently used spring boot application starters.: Used in Web, REST and Spring MVC applications.: Used in spring security application.: Used in Spring Web Services.: Used for Java Mail Support in spring framework.: Used in Spring Framework Test application.: Used in JDBC integration with Spring Framework.: Used in Java Bean Validation with Hibernate Validator.: Used in Thymeleaf integration with Spring Framework.: Used in Spring Data JPA with Hibernate.: Used in FreeMarker integration with Spring Framework.I am done now. Happy Spring Boot learning!