© Felipe Gutierrez 2016

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

5. Spring with Spring Boot

Felipe Gutierrez

(1)Albuquerque, New Mexico, USA

This chapter shows you how an old Spring developer used to do applications and compare them to Spring Boot. It also shows you how to use legacy Spring code with your Spring Boot applications.

Why this is important? I’ve been asked by several developers why Spring Boot is better than Spring or if Spring Boot will get rid of the Spring Framework. Remember that I said in the first chapters that Spring Boot is Spring, and you need to think of it as a new way to create the next generation of Spring applications.

Spring Web Applications

Let’s start by creating the same simple web application from the other chapters that will print out “Spring Rocks!”, this time using just Spring. First you need to know a little bit of background on the J2EE web and Spring MVC, because it’s the base for all Spring web applications. If you already know about it, feel free to skip to the next sections.

J2EE Web Applications

Creating a Java web application hasn’t been an easy task since the beginning. I explained in Chapter 1 that you need to get a lot going even before you can run your application, but let’s get started. You are going to create a J2EE web application, a servlet application, in an “old-fashion” way, using Maven archetypes with a servlet 2.4 specification. If you recall, the servlet was the first attempt to use a server side request to produce some HTML content.

You are going to use Maven, so make sure you have it in your PATH. Let's start by creating the web project template by executing this command:

$ mvn archetype:create -DgroupId=com.apress.j2ee -DartifactId=simple-web-app -DarchetypeArtifactId=maven-archetype-webapp

This command will create a simple-web-app folder with the structure shown in Figure 5-1.

A340891_1_En_5_Fig1_HTML.jpg
Figure 5-1. A simple-web-app structure

Figure 5-1. shows you the result of executing the maven command. Let’s start by adding a missing dependency in the pom.xml. Listing 5-1 shows you the final pom.xml.

Listing 5-1. simple-web-app/pom.xml
<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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>


        <groupId>com.apress.j2ee</groupId>
        <artifactId>simple-web-app</artifactId>
        <packaging>war</packaging>


        <version>1.0-SNAPSHOT</version>
        <name>simple-web-app Maven Webapp</name>
        <url>http://maven.apache.org</url>


        <dependencies>
               <dependency>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                        <version>2.4</version>
                        <scope>provided</scope>
                </dependency>
                <dependency>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                        <version>3.8.1</version>
                        <scope>test</scope>
               </dependency>
        </dependencies>
        <build>
                 <finalName>simple-web-app</finalName>
        </build>
 </project>

The missing dependency was the servlet-api artifactId, and this is because you need to create a servlet class.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
        <scope>provided</scope>
 </dependency>

Another important part of the pom.xml file is the <packaging> tag. It tells Maven that this will be a Web ARchive or WAR. Next, let’s create the servlet class. See Listing 5-2.

Listing 5-2. src/main/java/com/apress/j2ee/SimpleServlet.java
package com.apress.j2ee;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SimpleServlet extends HttpServlet {
       protected void service(HttpServletRequest request, HttpServletResponse response) throws
                                            ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Simple Web Application with Java</h1>");
        out.println("</body>");
        out.println("</html>");
      }


}

Listing 5-2 shows you the SimpleServlet class, which needs to be in the src/main/java/com/apress/j2ee path. The SimpleServlet is its method service and uses the PrintWriter class as a response for any request. Now you need to define the URL pattern that will use this servlet class. The URL pattern needs to be defined in the web.xml that is located in the WEB-INF folder. To be more specific, you need to edit the src/webapp/WEB-INF/web.xml file to declare the servlet class. See Listing 5-3.

Listing 5-3. src/webapp/WEB-INF/web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
         <servlet-name>SimpleServlet</servlet-name>
         <display-name>SimpleServlet</display-name>
         <description>A simple Servlet</description>
         <servlet-class>com.apress.j2ee.SimpleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
         <servlet-name>SimpleServlet</servlet-name>
         <url-pattern>/SimpleServlet</url-pattern>
  </servlet-mapping>
</web-app>

Listing 5-3 shows the web.xml file where you declare two sections—one is the name of the servlet, with the <servlet> tag. The other is the servlet mapping with the <servlet-mapping> tag where you add the URL that will be the endpoint of the request. In this case, it’s the /SimpleServlet.

Now you can execute the following command to package your web application:

$ mvn clean package

This command will create the target/simple-web-app.war file. Now you need to look for an application server. You can use Pivotal tcServer ( https://network.pivotal.io/products/pivotal-tcserver ) or you can use Tomcat ( http://tomcat.apache.org/ ). Or, if you are using a Mac/Linux, you can use brew ( http://brew.sh/ ) by executing:

$ brew install tomcat

Place your WAR in your <tomcat-installation>/webapps/ directory and run your application server. To run your application server, you can go to the <tomcat-installation>/bin directory and execute the startup.sh script. Then you can go to your web browser and access http://localhost:8080/simple-web-app/SimpleServlet. You should see this text:

Simple Web Application with Java

Of course, you can use an IDE of your preference and import this Maven project to facilitate the creation of the servlet class and to edit the other files—you are more than welcome to do so. My point here is that either you choose and IDE or you do this manually like I showed you. It’s still a hassle to create just a simple web application. This was the daily task for a web developer at least a decade ago.

After servlets, the JavaServer Pages (JSP) were born, but of course, J2EE evolved more and more. With its Servlet 3 specification, it provides a new configuration-less way for creating a web application by creating the @WebServlet that allows you to annotate your servlet class without a web.xml file.

Spring MVC Applications

The Spring Framework brought a new way to develop web applications by introducing a MVC (Model View Controller) pattern into the framework that is easy to set up and use. I know that the MVC was invented in the 70s and modeled by other frameworks and other programming languages even before the Spring Framework, but the Spring team did an excellent job using this pattern as a base model for every web application by simplifying its functionality.

Let’s take a look at a Spring MVC application and its parts. You can use the previous Maven archetype:

$ mvn archetype:create -DgroupId=com.apress.spring -DartifactId=simple-web-spring-app -DarchetypeArtifactId=maven-archetype-webapp

You are going to modify this because this particular Maven archetype is kind of old, but is useful just to create the files and directory structure. For example, you should change the web.xml version from 2.3 to 2.5, because you are going to use the Servlet 2.5 specification. This is one of the many hassles from J2EE. Now take a look at the final pom.xml in Listing 5-4.

Listing 5-4. pom.xml
<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>org.springframework.samples.service.service</groupId>
        <artifactId>simple-web-spring-app</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>


        <properties>

                <!-- Generic properties -->
                <java.version>1.8</java.version>
                <!-- Web -->
                <jsp.version>2.2</jsp.version>
                <jstl.version>1.2</jstl.version>
                <servlet.version>2.5</servlet.version>


                <!-- Spring -->
                <spring-framework.version>3.2.3.RELEASE</spring-framework.version>
        </properties>


        <dependencies>

                <!-- Spring MVC -->
                <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-webmvc</artifactId>
                        <version>${spring-framework.version}</version>
                </dependency>

                <!-- Other Web dependencies -->
                <dependency>
                        <groupId>javax.servlet</groupId>
                        <artifactId>jstl</artifactId>
                        <version>${jstl.version}</version>
                </dependency>
                <dependency>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                        <version>${servlet.version}</version>
                        <scope>provided</scope>
                </dependency>
                <dependency>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                        <version>${jsp.version}</version>
                        <scope>provided</scope>
                </dependency>
        </dependencies>


        <build>
                <finalName>simple-web-spring-app</finalName>
        </build>


</project>

Listing 5-4 shows you the pom.xml that you will use for this application. Take a moment and analyze the differences from Listing 5-1. You will see that you are now using the Spring MVC version 3.2.3.RELEASE and some other dependencies like the tag libraries. Right now the Spring MVC is in its version 4.2 (it’s simpler), but I wanted to show you how Spring developers used to do Spring web applications.

Next, let’s look at web.xml. Modify it to look the same as the one in Listing 5-5.

Listing 5-5. src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">


    <display-name>simple-web-spring-app</display-name>
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

Listing 5-5 shows you the web.xml. Remember that it must be exactly the same. Just take a look and compare it to Listing 5-3. First the version is now 2.5 (normally this was an indication of the servlet engine you will use), next there is the servlet declaration that adds the org.springframework.web.servlet.DispatcherServlet class that is the main dispatcher that will trigger the MVC pattern. As an additional declaration, the <init-param> tag will look for an XML configuration file, in this case WEB-INF/mvc-config.xml. This file is a Spring context configuration.

Next, take a look at the Spring configuration shown in Listing 5-6.

Listing 5-6. src/main/webapp/WEB-INF/mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


         <bean name="/showMessage.html"
                class="com.apress.spring.SimpleController" />


        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/WEB-INF/view/"/>
                <property name="suffix" value=".jsp"/>
        </bean>


</beans>

Listing 5-6 shows you the XML configuration. This is a typical Spring configuration where you define your bean (POJO-Plain Old Java Objects) classes that will be instantiate the Spring container. If you take a look at this XML, you will find that there is a bean and its name is /showMessage.html and it’s pointing to the com.apress.spring.SimpleController Java class (you are going to see the code soon). This particular declaration is the URL that will map to the class to be executed when there is a request to the /showMessage.html URL. There is also another bean declaration that is mandatory, because this is where you define your views by declaring the InternalResourceViewResoulver class. In this case, every view will be located at the /WEB-INF/view and every page will have the.jsp extension. This is very useful for security reasons, because you don’t want to have access to the root folder and extract your pages.

Next look at the SimpleController class in Listing 5-7.

Listing 5-7. src/main/java/com/apress/spring/SimpleController.java
package com.apress.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;


public class SimpleController extends AbstractController{

        @Override
        protected ModelAndView handleRequestInternal(HttpServletRequest request,
                HttpServletResponse response) throws Exception {


                ModelAndView model = new ModelAndView("showMessage");
                model.addObject("message", "Spring MVC Web Application");
                return model;
        }
}

Listing 5-7 shows you the SimpleController class. This class extends from the AbstractController class that has all the logic to manage your request (/showMessage.html). There is an override of the handleRequestInternal method that will respond by returning a ModelAndView instance that contains the information of what view to display. It carries some data in the message variable, in this case the text “Spring MVC Web Application”.

Next, let’s see the actual view that was declared in the controller with the code:

ModelAndView model = new ModelAndView("showMessage");

This line tells the Spring MVC that the view will be the showMessage, which is actually located at /WEB-INF/view/showMessage.jsp. The page display will be handled by the InternalResourceViewResolver class, as shown in Listing 5-8

Listing 5-8. src/main/webapp/WEB-INF/view/showMessage.jsp
<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
        <head>
                <meta charset="utf-8">
                <title>Welcome</title>
        </head>
        <body>
                <h2>${message}</h2>
        </body>
</html>

Listing 5-8 shows you the showMessage.jsp file. What is interesting here is the <h2> tag that contains the ${message} declaration. This declaration will be executed and translated to the attribute that comes from the controller when you declare the following in Listing 5-7:

model.addObject("message", "Spring MVC Web Application");

So, Spring will render the "Spring MVC Web Application" message. Now, if you package your application with the following:

$ mvn clean package

You will have the target/simple-web-spring-app.war file. Now you can use the application server of your preference and deploy it. Once it’s deployed you can access it in the web browser using the http://localhost:8080/simple-web-spring-app/showMessage.html URL and it will show the "Spring MVC Web Application" message. And that’s it; it’s a simple Spring MVC application!

If you already know Spring MVC, you may notice that I showed you a very old way to do it. Spring MVC versions 2.5, 3, and 4 allow you to add annotations to avoid extending from other classes and have more mapping in one single class. Take a look at Listing 5-9, which shows a better version of the controller using annotations.

Listing 5-9. src/main/java/com/apress/spring/SimpleController.java using annotations
package com.apress.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/showMessage.html")
public class HelloWorldController{
        @RequestMapping(method = RequestMethod.GET)
        public ModelAndView helloWorld(){
                ModelAndView model = new ModelAndView("showMessage");
                model.addObject("message", "Spring MVC Web App with annotations");
                return model;
        }
}

Listing 5-9 shows you a newer version of the Spring MVC where you can use annotations and remove extra configuration from the XML file. See Listing 5-10.

Listing 5-10. src/main/webapp/WEB-INF/mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


         <context:component-scan base-package="com.apress.spring" />

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/WEB-INF/view/"/>
                <property name="suffix" value=".jsp"/>
        </bean>


</beans>

Listing 5-10 shows you the mvc-config.xml file where now it's using the <context:component-scan> tag. Look at the com.apress.spring package level (sub-packages too) to find the marked classes. In this case it will find the SimpleController class because it’s marked with the @Controller annotation. You can see that there is no more bean definitions about the request mapping; everything is now handled by the SimpleController class and its annotations, such as @RequestMapping.

As you can see, the Spring Framework and in this case the Spring MVC technology has evolved over the years, making it easier for developers to create Web applications.

Spring Boot Web Applications

Now it’s Spring Boot’s turn. You are going to use the same simple web application. You can use the minimal Spring Boot app in Groovy, as shown in Listing 5-11.

Listing 5-11. app.groovy
@RestController
class WebApp{


    @RequestMapping("/showMessage.html")
    String greetings(){
        "Spring Boot MVC is easier"
   }
}

Listing 5-11 shows you the minimal Spring Boot web application. Just run it with the following command:

                  $ spring run app.groovy                                              

Now you can open a browser and go to http://localhost:8080/showMessage.html. That was so easy! No Maven, no web.xml, no bean declarations, no configuration of any kind! That’s the power of Spring Boot; it’s an opinionated technology that allows you to create applications with ease.

But wait, let’s do this simple web application using Maven. I mean, you are going to have at some point several classes and at least you need to have some structure, right?

In the previous chapter, you learned how to create a base template for Spring Boot using the Spring Boot CLI, remember? So open a terminal, create a folder ( simple-web-spring-boot), and execute the following command:

$ mkdir simple-web-spring-boot
$ cd simple-web-spring-boot
$ spring init -d=web -g=com.apress.spring -a=simple-web-spring-boot --package-name=com.apress.spring -name=simple-web-spring-boot -x

This command will create the base for your Spring Boot web application.

  • The -d=web tells the CLI to include the web dependency (spring-boot-starter-web)

  • The -g=com.apress.spring is the groupId

  • The -a=simple-web-spring-boot-app is the artifactId

  • The --package-name=com.apress.spring is the package name convention for the classes

  • The -name=simple-web-spring-boot-app is the name of the application

  • The -x will extract the template in the current directory; if you omit the extract option, you will find a simple-web-spring-boot-app.zip file

Your file structure should be similar to the one in Figure 5-2.

A340891_1_En_5_Fig2_HTML.jpg
Figure 5-2. Spring Boot structure after running the spring init command

Now you can open SimpleWebSpringBootApplication.java and modify it to look the same as Listing 5-12.

Listing 5-12. src/main/java/com/apress/spring/SimpleWebSpringBootApplication.java
package com.apress.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;


@RestController
@SpringBootApplication
public class SimpleWebSpringBootApplication {


        @RequestMapping("/showMessage.html")
        public String index(){
                return "Spring Boot Rocks!";
        }


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

Listing 5-12 shows the modified SimpleWebSpringBootApplication.java, where it's marked as a web rest controller with the @RestController annotation and it defines an index method marked with @RequestMapping. This will accept all incoming requests to the /showMessage.html URL. You are familiar with @SpringBootApplication, which will trigger the auto-configuration. It’s based on your classpath and the main method that will execute the application by calling the SpringApplication.run method. Remember, when you run the application it will lunch an embedded Tomcat and will start listening on port 8080.

To run it, just execute the following command:

$ ./mvnw spring-boot:run

This command will run the application, so open the browser and go to the http://localhost:8080/showMessage.htmlURL. You will see the message: “Spring Boot Rocks!”. I showed you that when you use the CLI, it will access the start.spring.io URL and build and download your template. The cool thing is that it brings Maven or Gradle wrappers, so you don’t need to install them. I know that in the previous examples I told you that you need to have Maven installed, right? So you are correct, you can run:

$ mvn spring-boot:run

Now you know more about old Java vs. Spring MVC vs. Spring Boot. Spring Boot still uses Spring MVC as the base for web applications, but in a very easy way. One of the major differences of Java/Spring MVC is that you get rid of the configuration files. No more XML files to deal with.

Of course, you will have some legacy Spring applications and you might want to incorporate some of these with your new Spring Boot applications. Let’s see how you could use your existing Spring apps with Spring Boot.

Using Spring with Spring Boot

This section shows you how to use existing Spring apps in Spring Boot applications. Remember that Spring Boot is Spring, so this is an easy task, but let’s start by considering the Spring container and the configurations and how you can use them in Spring Boot.

The Spring Framework in its first versions had a heavy dependency on XML configuration files. After Java 5 came into being, the Java configuration (annotations) was another mechanism used to configure the Spring container with the @Configuration(as marker for classes) and the @Bean annotations (for declaring the bean instances). Spring Boot follows the same pattern—you can use XML or annotation with Spring Boot.

XML with Spring Boot

If you have already several XML configuration files, you can integrate them with just one annotation in your main application. The org.springframework.context.annotation.ImportResource annotation accepts an array of string types to add the XML definitions.

If you are a Spring developer, you will recognize that this particular annotation was introduced in Spring version 3 and it hasn’t changed. Your Spring Boot application will import your resources with ease. For example, you can declare the following in the main app or in a configuration class:

@ImportResource({"META-INF/spring/services-context.xml","META-INF/spring/repositories-context.xml"})
@SpringBootApplication
public class SpringXmlApplication {
        @Autowired
        TaskRepository task;


        @Autowired
        ServiceFacade service;


        //More logic...
}

This code shows how you can use existing XML configuration files in your main Spring Boot application (or maybe you have already some Java config that you need to use):

@ImportResource("classpath:applicationContext.xml")
@Configuration
public class SimpleConfiguration {
        @Autowired
        Connection connection;  //This comes from the applicationContext.xml file.


        @Bean
        Database getDatabaseConnection(){
        return connection.getDBConnection();
             }


             // Mode code here....
}

This code shows how you can reuse your XML in an existing Java configuration class. You can also use a main class method to use your existing XML file:

public class Application {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext ctx = new SpringApplication("/META-INF/spring/integration.xml").run(args);
        System.out.println("Hit Enter to terminate");
        System.in.read();
        ctx.close();
    }
}

This example is related to the Spring Integration technology, where all the integration beans are working in the background.

Groovy Beans in Spring Boot

Another nice feature is that you can use the Groovy DSL (Domain Specific Language) for creating beans. This idea was taken from the Grails project, which is still very active and uses Spring as a base. In the upcoming version, it will include Spring Boot. With this Groovy beans DSL, you can create your Spring beans without the XML clutter. See Listing 5-13.

Listing 5-13. app.groovy
@RestController
class SimpleWebApp {


    @Autowired
    String text


    @RequestMapping("/")
    String index() {
         "You can do: ${text}!"
    }
}


beans {
      text String, "Spring Boot with Groovy beans"
}

Listing 5-13 shows you the beans DSL that you can use as well. In Chapter 18 of the book “Introducing Spring Framework” from Apress Publishing, I provided a small introduction to the Groovy DSL syntax. See that chapter if you want to get more familiar with it. You can run Listing 5-13 as usual:

$ spring run app.groovy

Point your browser at http://localhost:8080. You will get "You can do: Spring Boot with Groovy beans". So, you have ways to reuse Spring XML files or use the Groovy syntax to create some configurations.

Standalone Spring Apps vs. Spring Boot Apps

Not all applications are web apps; sometimes you need to run your Spring application in standalone mode without any server. You simply run it as a regular service or as a job and finish. To run a Spring application, you normally use the following code in your main method:

public static void main(final String[] args) {
    final ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/app-ctx.xml");
    final Service service = context.getBean(ServiceFacade.class);


        //Some process to run here
        //Extra work here
}

This code is using the ApplicationContext interface and the ClassPathXmlApplicationContext class to load the beans and initialize the container. After that you can use your beans by using the getBean method. Then you can do some process or call some functions and finish. In Spring Boot, it’s a little different. In order to execute some code after the Spring Boot is initialized and running, you have some choices, as shown in Listing 5-14.

Listing 5-14. SpringBoot Example, Implementing the CommandLineRunner Interface
package com.apress.spring;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public MyApplication implements CommandLineRunner {
    public void run(String... args) {
        // This will run after the SpringApplication.run(..)
        // Do something...
    }


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

Listing 5-14 shows you how you can run some processes or jobs after SpringApplication.run is called, by implementing the org.springframework.boot.CommandLineRunner interface and implementing the run(String... args) method. This is useful when you want to execute jobs or services, such as send a notification about the application or execute a SQL statement to update some rows before your application runs. This is not a web application; it is a standalone app.

Another alternative is to use the following code:

@Bean
public CommandLineRunner runner(){
    return new CommandLineRunner() {
        public void run(String... args){
            //Run some process here
        }
    };
}

This code shows you how to use the CommandLineRunner interface as a bean by marking the method with @Bean annotation. Or, if you are using Java 8, you can use the lambdas feature like this:

@Bean
public CommandLineRunner runner(Repository repo){
    return args -> {
        //Run some process here
    };
}

This code shows you how to use the CommandLineRunner interface using the Java 8 lambdas. In this case the method’s parameter is a Repository, which is normally useful to do some database tasks.

Maybe you are wondering what you need to do if you need to run some code even before the CommandLineRunner. You can do this by returning an InitializingBean interface.

@Bean
InitializingBean saveData(Repository repo){
    return () -> {
        //Do some DB inserts
    };
}

This code shows you how to execute some code even before the CommandLineRunner. Perhaps you need to initialize a database before you run tasks on it. This can be helpful for testing purposes. Don’t worry too much, I’ll show you more detail and with some complete examples in the following chapters.

Using Spring Technologies in Spring Boot

I showed you in the previous sections of this chapter that Spring Boot is Spring, and you can use any Spring beans defined in a XML or a Java Configuration class. But what about some of the Spring technologies, such as Spring JMS, Spring AMQP, Spring Integration, Spring Caching, Spring Session, Spring Rest, etc.?

The following chapters show you how to use all these technologies in more detail, but I can tell you now that the auto-configuration is the base of this, which means all the new annotations that Spring Framework version 4 uses. The key here is to get used to some of the annotations that allow you to use these technologies very easily.

The only thing you need to know now is that there is an annotation called @Enable<Technology> for each of these technologies; see Table 5-1.

Table 5-1. Spring Technologies Used in Spring Boot

Annotation

Description

@EnableJms

Messaging with JMS technology

@EnableCaching

Caching abstraction

@EnableRabbit

Messaging for the AMQP with RabbitMQ

@EnableBatchProcessing

Spring batch

@EnableWebSecurity

Spring security

@EnableRedisHttpSession

Spring session

@EnableJpaRepositories

Spring data

@EnableIntegration

Spring integration

Table 5-1 shows you some of the @Enable<Technology>annotations that will be required when you want to create applications and use some of these Spring technologies. You’ll learn more about these annotations during the course of this book.

Summary

This chapter explained the differences between old Java web apps, Spring MVC, and the new way, the Spring Boot way, to create web applications.

You learned how to use legacy or existing Spring apps along with Spring Boot, using either XML or Java configuration annotations. You also learned about multiple ways to run Spring Boot apps and execute code after the SpringApplication.run method executes and even before the CommandLineRunner interface with its run method executes.

You learned how to use all the Spring technologies by simply using the @Enable<Technology>. All these are covered in more detail in the following chapters.

In the next chapter, you are going to learn how to test your Spring Boot 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.235.176