Tuesday, May 2, 2017

Spring Boot 1.5 Tutorial: How to Create A Simple Web App

Spring Boot is a comprehensive Java application development framework. This tutorial will show you how to create a simple Java web app using Spring Boot. Spring Boot allows you to develop:
  • web applications: all from traditional, dynamic AJAX with HTML5 and JavaScript, and also server-side push
  • REST API services: you can access these servers and transfer data using JavaScript HTTP clients, AngularJS, Postman, REST API clients, and also other web servers
  • microservices: self-contained small applications that can be deployed using Docker or to Platform-as-a-Service infrastructure such as Pivotal CloudFoundry, IBM Bluemix, Red Hat OpenShift, or your own custom servers
Spring Boot 1.5 is the latest version and comes with features that make it easier to develop Java web apps compared to previous versions and especially when compared to configuring and wiring Spring applications manually.

Why Spring Boot?

The advantage of using Spring Boot is it's easy and fast to get started. Spring Boot provides most of the necessary components/dependencies and wiring them all together so you can create your app faster and deploy it in less time.

Spring Boot Modules

Spring provides many ready-to-use modules "out-of-the-box". What I mean by out-of-the-box here is not that your application will be bloated! In fact, your application will be very lean by default. However, you can add more modules as you see fit, and these modules will usually just work with your app with very little configuration. Let's see some modules that you can integrate with your app. I try to be as comprehensive as possible so let me know if I miss anything.

Core Spring Boot Modules

  • Spring Security. It allows you to secure your application via username and password credentials. This secures your web application, REST API endpoints, as well as JMX / Spring Boot Actuator endpoints. By default Spring Boot will autoconfigure a username called "user" and a random password that will be displayed on your application's console log. After that you can configure further by integrating with RDBMS database via JDBC, OAuth, or other means.
  • AOP. This provides aspect-oriented programming support via spring-aop or AspectJ. I don't really use AspectJ often but some of you may like it due to its flexibility for cross-cutting code injection support.
  • Transactions / JTA. A lot of you will be happy with built-in database Entity Manager transactional support provided by your JPA provider (default is Hibernate in Spring Boot). However if you need more, you can use Atomikos, Bitronix, or Narayana, that can provide JTA distributed transactions. This happens without the use of a Java EE app server. So you can still deploy using the self-contained Spring Boot app or to a plain "lightweight" web servlet container such as Tomcat.
  • Cache. I would avoid caching in the first stages of app development, but later on when you have many requests and you need caching support, Spring Boot allows you to integrate this functionality quickly. It can support in-memory Spring Caching and you can also configure other cache such as EHCache and JCache-compliant providers such as Apache Ignite and Hazelcast. It's possible to use Redis and memcached with some work.
  • DevTools. Some tools to make development work easy, debugging, diagnostics.
  • Configuration Processor. This module allows you to generate metadata for the configuration keys that you define yourself, other than the configuration keys already built-in from Spring Boot.
  • Validation. JSR-303 validation support using annotations. You'll need this either for JPA/document entities or for JSON REST API processing, or both. Note that by adding Web support you'll get this module too.
  • Session. Provides the API and implementations for storing and manipulating user sessions in the servlet container or better: the database. You can use standard RDBMS database but it's recommended to store session data in a fast in-memory storage such as Redis or memcached. Spring provides easy way to support Redis, which is expected as Redis has tight development relationship with Pivotal Software (although now it's somehow independent with Redis Labs).
  • Retry. Allows you to retry failed database transactions and other operations in a graceful manner.
  • Lombok. In my opinion it's a futuristic Java annotation library which allows you to perform several useful operations and structure code in a more compact and easy-to-understand way than plain Java, through constructs that feel like language extensions. I feel it's a bit risky for now but your development team may think its usefulness outweight the risks, so there's an option for you.

Web

  • Spring Web. Gives you the powerful Spring Web MVC web framework and Tomcat web server by default. You can also switch to Jetty or JBoss Undertow if you want.
  • Reactive Web. This is a future development for Spring Boot 2.0 that supports reactive web development, using Netty and Spring WebFlux. Very interesting, but if you want stability I suggest you to wait.
  • Websocket. Adds support for asynchronous server-side push interactions using Websocket technology which can also fallback to older mechanism with SockJS. STOMP via Websocket is supported as messaging protocol.
  • Web Services. SOAP is used in some enterprise environments so you can build contract-first (WSDL) SOAP web services with Spring. You can also create XML/SOAP Web Service clients with Spring (usually using proxies).
  • JAX-RS (RESTful API). JAX-RS is the Java API to write RESTful API servers and clients. Spring provides you the choice to use either Jersey or Apache CXF implementation. Note that you don't have to use JAX-RS to work with REST APIs. Spring Web already contains features that allow you to implement REST API servers and clients and you can use it as an alternative to JAX-RS. Or use both if you like (not common, but possible).
  • Ratpack. While I haven't used it but Spring Boot provides support for Ratpack framework: Lean and powerful HTTP apps for the JVM.
  • Vaadin. Vaadin is a Java web application framework that allows you to write and design web UIs similar to how you build Swing GUI apps. It abstracts the low-level details of JavaScript, AJAX, etc. so you just focus on the functionality of the app via Java code. Spring Boot provides good Vaadin integration.
  • REST Repositories. With Spring Data you can expose database entities easily from SQL DBMS databases or document databases, but still programmatically. With Spring REST Repositories support you can access these entities via REST API with minimal code. You definitely need to add Spring Security module as well, otherwise your database entities won't be secured.
  • HATEOAS. Allows you to build RESTful API services that adhere to HATEOAS principle (Hypermedia As The Engine Of Application State).
  • REST Repositories HAL Browser. Optional module that embeds a HAL Browser in your app, so you can inspect RESTful API endpoints just by using a browser. I don't really use this much as I prefer specialized tools like Postman for testing.
  • Spring Mobile. It makes development of mobile web applications simpler by providing device detection, and so on.
  • REST Docs. I have to admit I'm lousy at REST API documentation. Spring REST Docs is a tool for generating REST API documentation by combining manually written documentation and those generated automatically from API structure.
  • Stormpath. It integrates Stormpath authentication functionality with Spring Security, and provides Thymeleaf templates.

Template Engines

There are several template engines that Spring Boot supports. Thymeleaf is the one Pivotal promotes most, but you can use another template engine according to your preference.
  • Thymeleaf is the XML-based template engine with the best support with Spring MVC components.
  • Apache Freemarker. Very popular general purpose template engine that can be used well with Spring MVC.
  • Apache Velocity. Very mature general purpose template engine that also can be used with Spring MVC, though I personally prefer Freemarker.
  • Groovy Templates. You can use Groovy programming language to develop Spring Boot apps, and if so then using Groovy as the template engine may be natural to you.
  • Mustache. Template engine that is popular in the JavaScript world. In my opinion its template code looks good and with less clutter. However Mustache was not designed originally with Java in mind, so be prepared if there's lack of integration in some cases.
My favorite Java "template engine" is actually Apache Wicket, however it is not integrated by Spring Boot. However it is still possible to use Apache Wicket in Spring Boot with some configuration.

SQL Databases

Spring has excellent support for all kinds of RDBMS databases. And even those databases (and any exotic connector) not directly listed are can be supported as long as you have the proper JDBC driver.
  • JPA (Java Persistence API). This is mandatory for pretty much all web applications if you want to access the database. Spring Boot chooses Hibernate as default implementation but you can switch to EclipseLink.
  • JOOQ. JOOQ allows you to query database entities using fluent APIs.
  • MyBatis. You can also use MyBatis persistence library instead of Hibernate.
  • JDBC. JdbcTemplate support for accessing any SQL database with lower-level API.
  • JDBC Drivers: Spring Boot supports H2, HSQLDB, Apache Derby, MySQL, PostgreSQL, Microsoft SQL Server, and others.
  • Database migrations library. If you prefer a rigidly structured database migrations scheme that can potentially work across RDBMS implementations, choose Liquibase. Otherwise, Flyway will give you the most flexibility by writing RDBMS-specific SQL DDL/DML statements.

NoSQL

Spring Boot provides support for easy NoSQL database access through Spring Data project. This allows you to access NoSQL documents/entities using JPA-like object mapping and API. It makes it very quick to get started but there are also downsides to this approach: less flexibility and in some cases worse performance. That said, using Spring Data is not mandatory, you can always use the native driver/API, but this will forfeit conveniences provided by Spring Boot, like Spring Data REST Repositories support.

NoSQL databases readily supported by Spring Boot include:
  • MongoDB: You can use the standard MongoDB, or the Reactive MongoDB driver, and also use embedded MongoDB which is useful for testing.
  • Cassandra: Horizontally scalable columnar database.
  • Couchbase. Horizontally scalable database that stores documents using JSON structure and accessible via REST API as well.
  • Neo4j. Native Java graph database with good performance, indexing features, and optimized Cypher query language.
  • Redis. Fast key-value data store that works in-memory.
  • GemFire. Distributed data store supported well by Pivotal.
  • Full text search: Solr and Elasticsearch. Both search engines use Apache Lucene underneath, but the similarity end there. Both Solr and Elasticsearch are capable search engines that you can use, and Spring Boot makes it easy to integrate.

Cloud Modules

These modules allow you to connect, configure, and discover services in cloud environments such as Cloud Foundry and Amazon Web Services.

Social

Spring Boot provides integration with 3 social networks by way of Spring Social: Facebook, LinkedIn, and Twitter. With these modules, you can read posts and users from social media, and also post to Facebook wall and tweet. Before using any of these modules, you need to specify OAuth credentials and access token via application.properties configuration file.

I/O

Modules which provide enterprise integration and messaging functionality.
  • Mail (javax.mail). You'll use it in most of your apps to send email notifications to users, and you can also access POP3/IMAP inbox.
  • Message routing: Apache Camel and Spring Integration. Either of these modules allow you to integrate message routing with modular components. Spring Integration is more integrated with the Spring ecosystem, but Apache Camel is more flexible and also work very well with Spring. An advantage of Camel routes is that they can also work outside of Spring app, via a dedicated ESB such as JBoss Fuse. Camel also has Fuse IDE which allow you to design message routes visually.
  • JMS message broker. Spring Boot can support Apache ActiveMQ, Apache Artemis, and HornetQ as your preferred JMS message broker.
  • Spring Batch. Batch processing capability with an API that is also Java EE JSR-352.
  • Activiti. With this, you can integrate with BPMN workflow engine. Activiti is the BPMN engine used by Alfresco Enterprise Content Management System. Curious that Spring Boot doesn't provide built-in support for jBPM from JBoss.
  • RabbitMQ / AMQP 0.9.1. Spring Boot supports AMQP 0.9.1 message protocol that is used by RabbitMQ. Note that you also still use Apache Qpid AMQP message broker, although not so integrated.
  • Apache Kafka. Spring Kafka provides helpers to use Kafka messaging in more straightforward way.
  • LDAP. LDAP directory service protocol support. Spring Data LDAP allows you to access LDAP directory like accessing JPA entities.

Ops

  • Actuator. Actuator enables you to manage your Spring Boot application using JMX and REST APIs. Useful built-in endpoints are provided, and you're free to add custom Actuator endpoints. In addition, you can add Actuator Docs module to your Spring Boot project, to provide API documentation for these endpoints.
  • CRaSH Remote Shell (deprecated). This used to be a pretty useful functionality: you can SSH to your web application and perform maintenance tasks. Unfortunately, CRaSH project is no longer actively maintained so Spring developers decided to remove its support from Spring Boot 2.0 onwards.

Creating A Starter Web App

Now that we've known what Spring Boot modules are available, we're ready to start creating the app. Spring developers have provided Spring Initilizr, a scaffolding web app to generate a simple starter app project for you. Here's how to use it.

1. Go to http://start.spring.io and enter your project details

Go to http://start.spring.io.

Now you can enter some information about your project. These are optional but it's best that you get the names right from the first time. Renaming a project and all identifiers is not hard, but takes time and very boring.

2. Select the Spring Boot module dependencies

You can type in the autocomplete box or you can click "Switch to the full version" to get all choices so you can just tick checkboxes. I suggest you to pick: Security, Web.

I prefer to select as few dependencies as possible in the first step. Especially if you're new to Spring Boot, then a very simple first app is helpful. Adding more modules later is not complex, it's a simple matter of adding dependencies to the Maven pom.xml file. However, some modules (such as JPA for SQL database support) require application.properties configuration before you can use it. Configuring it takes simple steps, but you still have to know where to look. Unless you already know some Spring Boot configuration, it's best to leave the other modules unselected.

3. Click "Generate Project" and download the archived project

Extract the archived project inside a folder on your computer.

4. Test Running the App from Maven Command Line (Optional if you already use an IDE)

Even if you already use an IDE (which I'm sure most of you do), it's useful to know that Spring Boot projects can be run directly from the command line using Maven (if you don't have it yet, please download and make it runnable from your computer).

Use the command line, go to the Spring Boot project folder and type:

mvn spring-boot:run

For the first time, it will take some time to download Maven dependencies from the Internet. Then the app will start.
The app will show its console logs, which shows the autogenerated password (the username is "user"). You can visit the app using the browser here: http://localhost:8080/

While nothing meaningful will show up, if at least there are no errors and the web server is working well then you're good to go.

5. Import The Spring Boot Project into Your Java IDE

For convenient app development, a good Java IDE is necessary. All Java IDEs can import a Maven project easily.

Pivotal provides the Eclipse-based Spring Tool Suite IDE. However, I prefer IntelliJ IDEA from Jetbrains, which I think is a good choice if you're not sure what to pick, and there's a free Community edition available that is sufficient for simple apps. It's not a debate, any Java IDE will get the job done, they're all good. Each have strengths and weaknesses and I suggest that you get to know better with your IDE and explore alternatives that you see fit. But let's get back to the more important thing and that is to get the Spring Boot application development started.

After importing the project to the IDE, it will automatically download Maven dependencies from the Internet. You will also need to configure the JDK installed on your computer. Make sure there are no compiler or project errors.

From the IDE, you can Launch or Run the application which will display logging messages on the Console view. The logs show the autogenerated password (the username is "user"). Then you can check http://localhost:8080/ using your web browser.

Next Steps

This is just the first step but it demonstrates some important points with Spring Boot apps in general:

  • A starter app can be generated quickly with Spring Boot Initializr.
  • You don't need a servlet container or Java EE app server to run a Spring Boot app. A web server (Tomcat) is already built-in and you can run the project sources from command line using Maven.
  • Spring Boot is compatible with all Java IDEs: Eclipse, NetBeans, IntelliJ IDEA, Spring Tool Suite, even JBoss Developer Studio.
  • Spring Boot comes with convenient and sane defaults such as formatted logging using Logback. It's using the tools you may already know, preconfigured in a good way, and you still can customize if you like. But the boring little details have already been handled.
The plain empty web app needs some things to make it functional. Some things that can be added:
  • SQL Database access via JPA API and Spring Data JPA. By adding JPA and appropriate SQL driver such as MySQL or PostgreSQL, you can create database tables, insert and update rows, query for data, etc.
  • REST API Repositories. By using Spring Data API, you have the convenience of Spring Data REST Repositories, making your database entities accessible via REST APIs. Since you added Spring Security module, they're also secure by default.
  • Serve dynamic web pages with Thymeleaf/Freemarker/Velocity template engine. If you use purely client-side UI such as AngularJS, you won't need it. Otherwise, you can add a template engine such as Thymeleaf and start designing web UI, or use a component-based Java web framework such as Vaadin or Wicket.
I hope to cover tutorials for how to do these in the next articles.

Learn More

To learn more about Spring Boot, I highly recommend Spring Boot in Action:

No comments:

Post a Comment