© Felipe Gutierrez 2016

Felipe Gutierrez, Pro Spring Boot, 10.1007/978-1-4842-1431-2_1

1. Introduction to Spring Boot

Felipe Gutierrez

(1)Albuquerque, New Mexico, USA

Electronic supplementary material

The online version of this chapter (doi:10.​1007/​978-1-4842-1431-2_​1) contains supplementary material, which is available to authorized users.

It has been almost 13 years since the first beta release of the Spring Framework, which proved that you could create Java Enterprise applications without the complicated architecture that Sun Microsystems exposed to the world with the release of J2EE.

The Spring Framework was released as an open source project and was accepted well. It became the best open source framework for creating enterprise applications in a fast, reliable, and elegant way by promoting the use of design patterns and becoming one of the first frameworks to use the Dependency of Injection pattern. The Spring Framework has won a lot of awards in the open source community and keeps up to date by creating new features and embracing new technologies. This helps developers focus only on the application business-logic and leave the heavy lifting to the Spring Framework.

This chapter introduces the Spring Boot technology and gives you a very small taste of what it is and what you can do with it. You will learn about all its features and the associated “how-tos” during the course of the book. Let’s get started.

Spring Boot

I can easily say that Spring Boot is the next chapter of the Spring Framework. Don’t get me wrong, though; Spring Boot won’t replace the Spring Framework. That’s because Spring Boot is the Spring Framework! You can view Spring Boot as a new way to create Spring applications with ease.

Spring Boot simplifies the way you develop, because it makes it easy to create production-ready Spring-based applications that you can just run. You will find out that, with Spring Boot, you can create standalone applications that use an embedded server, making them 100% runnable applications. I will talk about this in several chapters of the book. One of its best features is that Spring Boot is an “opinionated” technology in that it will help you follow the best practices for creating robust, extensible, and scalable Spring applications.

You can find the Spring Boot project at http://projects.spring.io/spring-boot/ and very extensive documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/ . You can see the Spring Boot home page in Figure 1-1.

A340891_1_En_1_Fig1_HTML.jpg
Figure 1-1. Spring Boot home page ( http://projects.spring.io/spring-boot/ )

Spring Applications

If you are a Spring developer like me, you already know that in order to create a simple Spring web application, you must follow certain rules of the J2EE stack and some of the Spring Framework. Those rules include the following:

Create a folder structure that contains your WAR (Web ARchive):

  • It must contain a WEB-INF folder with lib and classes subfolders that contain the third-party libraries and your web application classes, respectively.

  • Some JSP (if needed), HTML, CSS, images, and JavaScript (if needed) files.

  • A file named web.xml that will contain the Spring org.springframework.web.servlet.DispatcherServlet class.

  • Your Spring beans in the form <servlet-name>-servlet.xml (of course, you can override this and add the complete location and name of your Spring beans).

Use a utility to package your WAR file. You can use the jar tool, but most people are more used to running Apache Maven, Gradle, or, if you are “old-school,” Apache Ant to compile, test, and create the WAR file.

Use an application server or container to run your WAR file, such as Tomcat, Jetty, Jboss, or WebSphere. Sometimes you need a dedicated server for deploying J2EE applications.

Even though it’s only a few steps, the reality is a more painful when you have a lot of resources and classes and a bunch of Spring beans that you need to include, wire up, and use. I’m not criticizing the way Spring web applications are developed, but I think it is more about what tool you use to help you avoid this particular hassle. Tools range from an IDE such as the STS tool ( https://spring.io/tools ) that helps you include the correct Spring XML schemas for declaring your beans, to external tools like YEOMAN ( http://yeoman.io/ ), which helps you create the structure and avoid the boilerplate to set everything up.

I’m talking about a simple Spring web application, but what happens when you need to include some persistence, or messaging, or perhaps you need to include security? Then you need an easy way to manage your dependencies. Of course, the easiest way is to download each dependency, but this can become a nightmare, at which point you’ll start looking for tools like Apache Maven or Gradle (a Groovy DSL for compile, build, and deploy use) to help you with these dependency management tasks.

Believe me, at some point it gets more difficult, and there should be a better way to develop Spring applications, right?

Spring Boot to the Rescue

Thanks to the amazing hard work of the Spring team, the first beta released two years ago gave amazing results. I was lucky to test it, and now with more added to it, it has become the “de facto” way to create Spring applications.

Instead of reading more about Spring Boot and how easy it is to use, take a look at the simplest Spring web application possible. See Listing 1-1.

Listing 1-1. app.groovy
@RestController
class WebApp{
      @RequestMapping("/")
      String greetings(){
        "<h1>Spring Boot Rocks</h1>"
     }
}

Listing 1-1 shows you a Groovy application and the simplest possible Spring web application. But why Groovy? Well, Groovy removes all the boilerplate of Java and, with a few lines of code, you have a web app. How do you run it? You simply execute the following command:

$ spring run app.groovy

You should have something like the following output:

.   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _
( ( )\___ | '_ | '_| | '_ / _` |
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.1.RELEASE)


INFO 62862 --- [runner-0] o.s.boot.SpringApplication               : Starting application on
INFO 62862 --- [runner-0] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
...
INFO 62862 --- [runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
INFO 62862 --- [runner-0] o.apache.catalina.core.StandardService   : Starting service Tomcat
INFO 62862 --- [runner-0] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
INFO 62862 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
INFO 62862 --- [ost-startStop-1] o.s.web.context.ContextLoader    : Root WebApplicationContext: initialization completed in 1820 ms
INFO 62862 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
...
INFO 62862 --- [runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) ...

You may be wondering: Wait a minute, what is this spring run command? How can I install it? What else do I need? Don’t worry too much; in the next chapter, you will install the Spring Boot CLI (Command Line Interface) and you will learn everything you need to know about this particular tool.

You can open a browser and point to http://localhost:8080 to see the message: Spring Boot Rocks.

How does the Spring Boot know about a web application and how to run it? Spring Boot inspects your code and, based on the annotations @RestController and @RequestMapping, tries to execute your code as a web application. It does this by using an embedded Tomcat server and running the web app from within. That’s it! It’s very simple to create a Spring web application.

Now let’s see the Java version, which is a minimal web app. I’ll show you only the code for now; in the next chapter, you’ll learn how to set it up. See Listings 1-2 and 1-3.

Listing 1-2. SimpleWebApp.java
package com.apress.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class SimpleWebApp {


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

Listing 1-2 shows you the entry point for a Spring Boot application in Java. It’s using a @SpringBootApplication annotation and the SpringApplication singleton class in the main method that will execute the application. The run method call accepts two parameters—the class that actually contains the annotated @SpringBootApplication annotation and the application’s arguments.

Listing 1-3. SimpleWebController.java
package com.apress.spring;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class SimpleWebController {


        @RequestMapping("/")
        public String greetings(){
                return "<h1> Spring Boot Rocks in Java too!</h1>";
        }        
}

Listing 1-3 shows you the typical Spring MVC controller class, where you use the @RestController and the @RequestMapping annotations to tell Spring to use the SimpleWebController class as a web controller and to use the method greetings as an entry point for a HTTP request.

You can run this example by using the Spring Boot CLI, the same as you did with the Groovy version. In this case, though, you are using the .java extension:

$ spring run *.java

Or, if you add the structure for Maven, you can run this example by using the following command:

$ mvn spring-boot:run

Or, if you have the Maven wrapper (discussed in the next chapter), you can run it with the following command:

$ mvn spring-boot:run

Or, if you set up the structure for Gradle, you can run it with this command:

$ gradle bootRun

Regardless of the method you use, open a browser and point to the URL http://localhost:8080/. You should see the message: “Spring Boot Rocks in Java too!”.

You may be wondering how to set this Java version up or how to use the Spring Boot CLI, right? Don’t worry, in the next chapter, you will see how to install and use the Spring Boot CLI to prototype Spring apps in the awesome programming language called Groovy (like Listing 1-1) and you will learn how to use Spring Boot to run Java-based Spring applications (like Listings 1-2 and 1-3) and how Spring Boot works internally.

For now, I simply wanted to show you that, with a few lines of code, you can create a simple Spring web application using Groovy or Java instead of all that hassle from the J2EE stack.

Note

If you want to use Spring Boot right away, feel free to use the book’s companion source code. The Java example contains the structure and everything you need to run the Maven wrapper: $ mvnw spring-boot:run.

Why Spring Boot?

Spring Boot has many features that make it suitable for:

  • Cloud Native Applications that follow the 12 factor patterns (developed by the Netflix engineering team at http://12factor.net/ )

  • Productivity increases by reducing time of development and deployment

  • Enterprise-production-ready Spring applications

  • Non-functional requirements, such as the Spring Boot Actuator (a module that brings metrics, health checks, and management easily) and embedded containers for running web applications (such as Tomcat, Undertow, Jetty, etc.)

The term “microservices” is getting attention for creating scalable, highly available, and robust applications, and Spring Boot fits there perfectly by allowing developers to focus only on the business logic and to leave the heavy lifting to the Spring Framework.

Spring Boot Features

Spring Boot has a lot of features that you’ll learn about in the following chapters, and here is just a taste:

  • The SpringApplication class. I showed you that in a Java Spring Boot application, the main method executes this singleton class. This particular class provides a convenient way to initiate a Spring application.

  • Spring Boot allows you to create applications without requiring any XML configuration. Spring Boot doesn’t generate code.

  • Spring Boot provides a fluent builder API through the SpringApplicationBuilder singleton class that allows you to create hierarchies with multiple application contexts. This particular feature is related to the Spring Framework and how it works internally. If you are a Spring developer already, you’ll learn more about this feature in the following chapters. If you are new to Spring and Spring Boot, you just need to know that you can extend Spring Boot to get more control over your applications.

  • Spring Boot offers you more ways to configure the Spring application events and listeners. This will be explained in more detail in the following chapters.

  • I mentioned that Spring Boot is an “opinionated” technology, which means that Spring Boot will attempt to create the right type of application, either a web application (by embedding a Tomcat or Jetty container) or a single application.

  • The ApplicationArguments interface. Spring Boot allows you to access any application arguments. This is useful when you want to run your application with some parameters. For example, you can use --debug mylog.txt or --audit=true and have access to those values.

  • Spring Boot allows you to execute code after the application has started. The only thing you need to do is implement the CommandLineRunner interface and provide the implementation of the run(String ...args) method. A particular example is to initialize some records in a database as it starts or check on some services and see if they are running before your application starts.

  • Spring Boot allows you to externalize configurations by using an application.properties or application.yml file. More about this in the following chapters.

  • You can add administration-related features, normally through JMX. You do this simply by enabling the spring.application.admin.enabled property in the application.properties or application.yml files.

  • Spring Boot allows you to have profiles that will help your application run in different environments.

  • Spring Boot allows you to configure and use logging very simply.

  • Spring Boot provides a simple way to configure and manage your dependencies by using starter poms. In other words, if you are going to create a web application, you only need to include the spring-boot-start-web dependency in your Maven pom or Gradle build file.

  • Spring Boot provides out-of-the-box non-functional requirements by using the Spring Boot Actuator, so you can see the health, memory, and so on, of your application.

  • Spring Boot provides @Enable<feature> annotations that help you to include, configure, and use technologies like databases (SQL and NoSQL), caching, scheduling, messaging, Spring integration, batching, and more.

As you can see, Spring Boot has all these features and more, and you’ll learn more about these features in the following chapters. Now it’s time to start learning more about Spring Boot by seeing how it works internally.

Summary

This chapter provided a quick overview of the Spring Framework and covered one of its new technologies: Spring Boot.

The following chapters start showing you all the cool features of Spring Boot, first by creating simple applications and understanding the internals of Spring Boot and then by creating more complicated applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.194