Monday, November 23, 2015

Spring boot - Getting started

Spring boot - Getting started


This article explains how to get started on Spring boot. Assuming you already have JDK, maven and eclipse installed in your PC, lets get started. 


Step 1: Create a simple maven project in eclipse.
Step 2: Create the following parent definition in pom
       <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>1.3.0.RELEASE</version>
       </parent>

Add the following dependencies
              <dependency>
                     <groupId>org.springframework.boot</groupId>
                     <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
Spring boot starter web dependency takes care of loading required jars for the web such as spring web etc., No more hassles on the need to remember the spring jars and version names.

Step 3: Create a simple web controller
@RestController
@EnableAutoConfiguration
public class SampleController {

       @RequestMapping("/")
       String home() {
              return "Hi Buddy";
       }
      
       public static void main(String args[]) {
              SpringApplication.run(SampleController.class, args);
       }
}
The EnableAutoConfiguration annotation informs boot to automatically configure required annotations based on the jars that you have added in your application. Cool isn’t it.
Run the Above Sample Controller as a java application
What just happened. When did I start the web server ??
Actually Spring boot takes care of that. When you actually run SpringApplication.run, it internally runs a web server and then loads the controller into that server.




Step 4: Invoke the controller in the web browser: 


Simple and easy to develop without having to worry about dependencies or the server. 

Now if you don’t want to add the parent pom for whatever reasons like you want to add your own project parent pom or so, you can add the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

You may also want to add the following to package your project as an executable jar.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>






No comments:

Post a Comment