Saturday, October 27, 2018

First Spring Boot Project - Hello World!

       

This section describes how to develop a simple “Hello World!” web application that highlights some of Spring Boot’s key features. We use Maven to build this project, since most IDEs support it.

Spring Initializer

One of the ways to Bootstrapping a Spring Boot application is by using Spring Initializer. To do this, you will have to visit the Spring Initializer web page www.start.spring.io and choose your Build, Spring Boot Version and platform. Also, you need to provide a Group, Artifact and required dependencies to run the application.
Observe the following screenshot that shows an example where we added the spring-boot-starter-web dependency to write REST Endpoints.
Once you provided the Group, Artifact, Dependencies, Build Project, Platform and Version, click Generate Project button. The zip file will download and the files will be extracted.
This section explains you the examples by using Maven.
Project that downloaded in the zip file need to be opened by the IDE. Project can be runned by the IDE and Command Prompt. 

Maven

After you download the project, unzip the file. The pom.xml is the recipe that is used to build your project. Open your favorite text editor and add the following:

























Adding Classpath Dependencies

Spring Boot provides a number of “Starters” that let you add jars to your classpath. Our sample application has already used spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-managementsection so that you can omit version tags for “blessed” dependencies.
Other “Starters” provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, we add aspring-boot-starter-web dependency. Before that, we can look at what we currently have by running the following command:
$ mvn dependency:tree

[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
The mvn dependency:tree command prints a tree representation of your project dependencies. You can see that spring-boot-starter-parent provides no dependencies by itself. To add the necessary dependencies, edit your pom.xml and add the spring-boot-starter-web dependency immediately below the parentsection:
<dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
</dependencies>
As mentioned above dependencies can be added to pom.xml file after creating project by adding dependencies.But we already add spring-boot-starter-web dependency when creating the project by Spring Initializer. You can see it below:
If you run mvn dependency:tree again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.

Controlling Maven and Java versions:

Before we begin, open a terminal and run the following commands to ensure that you have valid versions of Java and Maven installed:
$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
Maven and Java SDK must be installed for running application with command prompt. 

Ensure that define the maven and java sdk as enviroment variables. JAVA_HOME for java sdk and PATH for maven.
Adding to PATH: Add the unpacked distribution’s bin directory to your user PATH environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding or selecting the PATH variable in the user variables with the value C:\Program Files\apache-maven-3.5.4\bin. The same dialog can be used to set JAVA_HOME to the location of your JDK, e.g. C:\Program Files\Java\jdk1.7.0_51  %JAVA_HOME%\bin must be added to Path in the System Variables.

Writing the Code

In this example, the main class file is located at the src/java/main directories with the default package com.HelloWorld.demo. Observe the code shown here for a better understanding −


The @RestController and @RequestMapping Annotations:

The first annotation on our DemoApplication class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. In this case, our class is a web @Controller, so Spring considers it when handling incoming web requests.
The @RequestMapping annotation provides “routing” information. It tells Spring that any HTTP request with the / path should be mapped to the home method. The@RestController annotation tells Spring to render the resulting string directly back to the caller.

Create an Executable JAR

Let us create an executable JAR file to run the Spring Boot application by using Maven commands in the command prompt. You can run the application without creating executable jar file with using IDE. You should be inside the folder of project with using command prompt. Then enter mvn clean install command. With that a executable jar file must be created in the target file. To run it enter java -jar target\"executableFileName".jar command. If you open a web browser to localhost:8080, you should see the following output:


Friday, October 19, 2018

Introduction to Spring Boot

 What is Spring Boot?

            Spring Boot is an open source Java-based framework used to create a Micro Service. Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. We need to understand what is Spring framework before go further about Spring Boot. 
         Spring framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly.Basically Spring is a framework for dependency-injection which is a pattern that allows to build very decoupled systems.
         Over the years spring has become more and more complex as new functionalities have been added. Just visit the page-https://spring.io/projects and we will see all the spring projects we can use in our application for different functionalities. If one has to start a new spring project we have to add build path or add maven dependencies, configure application server, add spring configuration . So a lot of effort is required to start a new spring project as we have to currently do everything from scratch. Spring Boot is the solution to this problem. Spring boot has been built on top of existing spring framework. Using spring boot we avoid all the boilerplate code and configurations that we had to do previously. Spring boot thus helps us use the existing Spring functionalities more robustly and with minimum efforts.


Goals of Spring Boot:

  • To avoid complex XML configuration in Spring
  • To develop a production ready Spring applications in an easier way
  • To reduce the development time and run the application independently
  • Offer an easier way of getting started with the application

Features of Spring Boot:

  • It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions.
  • It provides a powerful batch processing and manages REST endpoints.
  • In Spring Boot, everything is auto configured; no manual configurations are needed.It sets up your application based on the surrounding environment, as well as hints what the developers provide.
  • It offers annotation-based spring application
  • Eases dependency management
  • It includes Embedded Servlet Container
  • Literally, it's completely standalone. Hence, you don’t need to deploy your application to a web server or any special environment. Your only task is to click on the button or give out the run command, and it will start.
  • It is Opinionated. This means that the framework chooses how to things for itself. This is the point where a lot of people says "wait a minute, I do not want to participate in it." Here I encourage you to wait for a second and hold your judgment for now, because, actually, it can be a good thing.
        Let's examine important and essential features more closely:
        

Intelligent Auto-Configuration

The intelligent auto-configuration attempts to auto-configure your application based on what dependencies you added. It is contextually aware and smart. Let’s see an example according to a database feature.
If you add a dependency to the pom.xml, which relates to a database, the framework assumes that you probably would like to use a database. Then, it auto-configures your application for database access.Furthermore, if the dependency appears for a very specific database, for example, Oracle or MySQL. It can make a more certain assumption and probably will configure that specific database access what you exactly need.
To set up auto-configuration is extremely effortless. You only need to add the  @EnableAutoConfiguration annotation to your Spring Boot application.
Observe the following code for better understanding:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

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

Being Standalone

You may think that running a Java application is easy — you simply give out the run command and everything works. To be honest, it is not that simple.
The Process of Starting a Java-Based Web Application:
  • First of all, you need to package your application.
  • Choose which type of web servers you want to use and download it. They are a lot of different solutions out there.
  • You need to configure that specific web server.
  • After that, you must organize the deployment process and start your web server.
With Spring Boot, you need the following process:
  • Package your application
  • Run it with some simple command like java -jar my-application.jar
Really, it's that simple.
Spring Boot takes care of the rest by starting and configuring an embedded web server and deploys your application there.

Opinionated

If you write Java applications, you have tons of choices, starting from the web, logging, collection framework, and the build tool you use.Despite this, in the most cases, the developers use the same most popular libraries. All that the Spring Boot does is that it loads and configures them in the most standard way. Hence, the developers don’t need to spend a lot of time to configure up the same thing over and over again.

@SpringBootApplication annotation:

The entry point of the Spring Boot Application is the class contains  this annotation. This class should have the main method to run the Spring Boot application. This annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations.
Observe the following code for a better understanding:
mport org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@ComponentScan annotation: 
Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project.
Observe the following code for a better understanding:
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

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