Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Spring Boot 2.0 Cookbook
Spring Boot 2.0 Cookbook

Spring Boot 2.0 Cookbook: Configure, test, extend, deploy, and monitor your Spring Boot application both outside and inside the cloud , Second Edition

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Spring Boot 2.0 Cookbook

Getting Started with Spring Boot

Spring Boot has a lot of starters that are already a part of the Spring Boot family. This chapter will provide you with an overview of http://start.spring.io/, available starter modules, and will also show you how to make a project Bootiful, as Josh Long likes to call it.

In this chapter, we will learn about the following topics:

  • Using a Spring Boot template and starter
  • Creating a simple application
  • Launching an application using Gradle
  • Using the command-line runners
  • Setting up a database connection
  • Setting up a data repository service
  • Scheduling executors

Introduction

In the fast-paced world of today's software development, the speed of application creation and the need for rapid prototyping are becoming more and more important. If you are developing a software using a JVM language, Spring Boot is exactly the kind of framework that will give you the power combined with the flexibility that will enable you to produce high-quality software at a rapid pace. So, let's take a look at how Spring Boot can help you to make your application Bootiful.

Using a Spring Boot template and starter

Spring Boot comes with over 40 different starter modules, which provide ready-to-use integration libraries for many different frameworks, such as database connections that are both relational and NoSQL, web services, social network integration, monitoring libraries, logging, template rendering, and the list just keeps going on. While it is not practically feasible to cover every single one of these components, we will go over the important and popular ones to get an idea of the possibilities and the ease of application development that Spring Boot provides us with.

How to do it...

We will start by creating a basic simple project skeleton, and Spring Boot will help us achieve this:

  1. Head over to http://start.spring.io
  2. Fill out a simple form with the details about our project
  3. Click on Generate Project alt + a premade project skeleton will download; this is where we begin

How it works...

You will see the Project Dependencies section, where we can choose the kind of functionalities that our application will perform: Will it connect to a database? Will it have a web interface? Do we plan to integrate with any of the social networks bake in operational support? and so on. By selecting the desired technologies, the appropriate starter libraries will be added automatically to the dependency list of our pregenerated project template.

Before we proceed with the generation of our project, let's go over what exactly a Spring Boot starter is and the benefits it provides us with.

Spring Boot aims to make it easy to get started with creating an application. Spring Boot starters are bootstrap libraries that contain a collection of all the relevant transitive dependencies that are needed to start a particular functionality. Each starter has a special file, which contains the list of all the provided dependencies Spring provides. Let's take a look at the following link for a spring-boot-starter-test definition as an example:

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-starters/spring-boot-starter-test/src/main/resources/META-INF/spring.provides

Here we will see the following code:

provides: spring-test, spring-boot, junit, mockito, hamcrest-library, jsonassert, json-path 

This tells us that by including spring-boot-starter-test in our build as a dependency, we will automatically get spring-test, spring-boot, junit, mockito, hamcrest-library,jsonassert, and json-path. These libraries will provide us with all the necessary things in order to start writing application tests for the software that we will develop, without needing to manually add these dependencies to the build file individually.

With more than 100 starters provided, and with the ongoing community additions increasing the list, it is very likely that unless, we find ourselves with the need to integrate with a fairly common or popular framework, there is already a starter out there that we can use.

The following table shows you the most notable ones so as to give you an idea of what is available:

Starter

Description

spring-boot-starter

This is the core Spring Boot starter that provides you with all the foundational functionalities. It is depended upon by all other starters, so no need to declare it explicitly.

spring-boot-starter-actuator

This starter provides you with a functionality to monitor, manage an application, and audit.

spring-boot-starter-jdbc

This starter provides you with a support to connect and use JDBC databases, connection pools, and so on.

spring-boot-starter-data-jpa

spring-boot-starter-data-*

The JPA starter provides you with needed libraries so you can use Java Persistence API (JPA): Hibernate, and others.

Various data-* family starters provide support for a number of datastores, such as MongoDB, Data REST, or Solr.

spring-boot-starter-security

This brings in all the needed dependencies for Spring Security.

spring-boot-starter-social-*

This allows you to integrate with Facebook, Twitter, and LinkedIn.

spring-boot-starter-test

This is a starter that contains the dependencies for spring-test and assorted testing frameworks: JUnit and Mockito, among others.

spring-boot-starter-web

This gives you all the needed dependencies for web application development. It can be enhanced with spring-boot-starter-hateoas, spring-boot-starter-websocket, spring-boot-starter-mobile, or spring-boot-starter-ws, and assorted template-rendering starters: sping-boot-starter-thymeleaf or spring-boot-starter-mustache.

spring-cloud-starter-*

Various cloud-* family starters providing support for a number of frameworks, such as Netflix OSS, Consul, or AWS.

Creating a simple application

Now that we have a basic idea of the starters that are available to us, let's go ahead and create our application template at http://start.spring.io.

How to do it...

The application that we are going to create is a book catalog management system. It will keep a record of books that were published, who the authors were, the reviewers, publishing houses, and so forth. We will name our project BookPub, and apply the following steps:

  1. First let's switch to the full version by clicking the link below the Generate Project alt + button
  2. Choose Gradle Project at the top
  3. Use Spring Boot version 2.0.0(SNAPSHOT)
  4. Use the default proposed Group name: com.example
  5. Enter bookpub for an Artifact field
  6. Provide BookPub as a Name for the application
  7. Specify com.example.bookpub as our Package Name
  8. Select Jar as Packaging
  9. Use Java Version as 8
  10. Select the H2, JDBC, and JPA starters from the Search for dependencies selection so that we can get the needed artifacts in our build file to connect to an H2 database
  11. Click on Generate Project alt + to download the project archive

How it works...

Clicking on the Generate Project alt + button will download the bookpub.zip archive, which we will extract from our working directory. In the newly created bookpub directory, we will see a build.gradle file that defines our build. It already comes preconfigured with the right version of a Spring Boot plugin and libraries, and even includes the extra starters, which we have chosen. The following is the code of the build.gradle file:

dependencies { 
  compile("org.springframework.boot:spring-boot-starter-data-jpa") 
  compile("org.springframework.boot:spring-boot-starter-jdbc") 
  runtime("com.h2database:h2") 
  testCompile("org.springframework.boot:spring-boot-starter-test")  
} 

We have selected the following starters:

  • org.springframework.boot:spring-boot-starter-data-jpa: This starter pulls in the JPA dependency.
  • org.springframework.boot:spring-boot-starter-jdbc: This starter pulls in the JDBC supporting libraries.
  • com.h2database: H2 is a particular type of database implementation, namely H2.
  • org.springframework.boot:spring-boot-starter-test: This starter pulls all the necessary dependencies for running tests. It is only being used during the test phase of the build, and it is not included during the regular application compile time and runtime.

As you can see, the runtime("com.h2database:h2") dependency is a runtime one. This is because we don't really need, and probably don't even want to know, the exact type of database to which we will connect at the compile time. Spring Boot will autoconfigure the needed settings and create appropriate beans once it detects the presence of the org.h2.Driver class in the classpath when the application is launched. We will look into the inner workings of how and where this happens later in this chapter.

The data-jpa and jdbc are Spring Boot starter artifacts. If we look in these dependency JARs once they are downloaded, or using Maven Central, we will find that they don't contain any actual classes, only the various metadata. The two containing files that are of interest are pom.xml and spring.provides. Let's first look at the spring.provides file in the spring-boot-starter-jdbc JAR artifact, as follows:

provides: spring-jdbc,spring-tx,tomcat-jdbc 

This tells us that, by having this starter as our dependency, we will transitively get the spring-jdbc, spring-tx, and tomcat-jdbc dependency libraries in our build. The pom.xml file contains the proper dependency declarations that will be used by Gradle or Maven to resolve the needed dependencies during the build time. This also applies to our second starter: spring-boot-starter-data-jpa. This starter will transitively provide us with the spring-orm, hibernate-entity-manager, and the spring-data-jpa libraries.

At this point, we have enough libraries/classes in our application classpath so as to give Spring Boot an idea of what kind of application we are trying to run and what type of facilities and frameworks need to be configured automatically by Spring Boot to stitch things together.

Earlier, we mentioned that the presence of the org.h2.Driver class in the classpath will trigger Spring Boot to automatically configure the H2 database connection for our application. To see exactly how this will happen, let's start by looking at our newly created application template, specifically at BookPubApplication.java, which is located in the src/main/java/com/example/bookpub directory in the root of the project. We do this as follows:

    package com.example.bookpub; 
 
    import org.springframework.boot.SpringApplication; 
    import org.springframework.boot.autoconfigure.
SpringBootApplication; @SpringBootApplication public class BookPubApplication { public static void main(String[] args) { SpringApplication.run(BookPubApplication.class, args); } }

This is effectively our entire and fully runnable application. There's not a whole lot of code here and definitely no mention of configuration or databases anywhere. The key to making magic is the @SpringBootApplication meta-annotation. In this, we will find the real annotations that will direct Spring Boot to set things up automatically:

    @SpringBootConfiguration 
    @EnableAutoConfiguration 
    @ComponentScan (excludeFilters = @Filter(type =  
FilterType.CUSTOM, classes = TypeExcludeFilter.class)) public @interface SpringBootApplication {...}

Let's go through the following list of annotations mentioned in the preceding code snippet:

  • @SpringBootConfiguration: This annotation is in itself a meta-annotation; it tells Spring Boot that the annotated class contains Spring Boot configuration definitions, such as the @Bean, @Component, and @Service declarations, and so on. Inside, it uses the @Configuration annotation, which is a Spring annotation, and not just Spring Boot, as it is a Spring Framework core annotation, used to mark classes containing Spring configuration definitions.
It is important to note that using @SpringBootConfiguration over @Configuration is helpful when executing tests with Spring Boot Test framework, as this configuration will automatically be loaded by the Test framework when the test is annotated with @SpringBootTest. As it is noted in the Javadoc, an application should only ever include one @SpringApplicationConfiguration, and most idiomatic Spring Boot applications will inherit it from @SpringBootApplication.
  • @ComponentScan: This annotation tells Spring that we want to scan our application packages starting from the package of our annotated class as a default package root for the other classes that may be annotated with @Configuration, @Controller, and other applicable annotations, which Spring will automatically include as part of the context configuration. The applied TypeExcludeFilter class provides filtering out for various classes to be excluded from ApplicationContext. It is mostly used by spring-boot-test to exclude classes that should be used only during tests; however, it is possible to add your own beans that extend from TypeExcludeFilter and provide filtering for other types that are deemed necessary.
  • @EnableAutoConfiguration: This annotation is a part of the Spring Boot annotation, which is a meta-annotation on its own (you will find that Spring libraries rely very heavily on the meta-annotations so they can group and compose configurations together). It imports the EnableAutoConfigurationImportSelector and AutoConfigurationPackages.Registrar classes that effectively instruct Spring to automatically configure the conditional beans depending on the classes available in the classpath. (We will cover the inner workings of autoconfiguration in detail in Chapter 4, Writing Custom Spring Boot Starters.)

The SpringApplication.run(BookPubApplication.class, args); code line in the main method basically creates a Spring application context that reads the annotations in BookPubApplication.class and instantiates a context, which is similar to how it would have been done had we not used Spring Boot and stuck with just a regular Spring Framework.

Launching an application using Gradle

Typically, the very first step of creating any application is to have a basic startable skeleton. As the Spring Boot starter has created the application template for us already, all we have to do is extract the code, build, and execute it. Now let's go to the console and launch the application with Gradle.

How to do it...

Change the location of our directory to where the bookpub.zip archive was extracted from and execute the following command from the command line:

      $ ./gradlew clean bootRun
  
If you don't have gradlew in the directory, then download a version of Gradle from https://gradle.org/downloads or install it via Homebrew by executing brew install gradle. After Gradle is installed, run wrapper in the gradle folder to get the Gradle wrapper files generated. Another way is to invoke $gradleclean bootRun.

The output of the preceding command will be as follows:

    ...
      .   ____          _            __ _ _
     /\ / ___'_ __ _ _(_)_ __  __ _    
    ( ( )___ | '_ | '_| | '_ / _` |    
     \/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |___, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::  (v2.0.0.BUILD-SNAPSHOT)
    
    2017-12-16 23:18:53.721 : Starting BookPubApplication on mbp with  
PID 43850
2017-12-16 23:18:53.781 : Refreshing org.springframework.context.
annotation.Annotatio
2017-12-16 23:18:55.544 : Building JPA container
EntityManagerFactory for persistence
2017-12-16 23:18:55.565 : HHH000204: Processing
PersistenceUnitInfo [name: default
2017-12-16 23:18:55.624 : HHH000412: Hibernate Core
{5.2.12.Final}
2017-12-16 23:18:55.625 : HHH000206: hibernate.properties not
found
2017-12-16 23:18:55.627 : HHH000021: Bytecode provider name :
javassist
2017-12-16 23:18:55.774 : HCANN000001: Hibernate Commons
Annotations {5.0.1.Final
2017-12-16 23:18:55.850 : HHH000400: Using dialect:
org.hibernate.dialect.H2Dialect
2017-12-16 23:18:55.902 : HHH000397: Using
ASTQueryTranslatorFactory
2017-12-16 23:18:56.094 : HHH000227: Running hbm2ddl schema
export
2017-12-16 23:18:56.096 : HHH000230: Schema export complete 2017-12-16 23:18:56.337 : Registering beans for JMX exposure on
startup
2017-12-16 23:18:56.345 : Started BookPubApplication in 3.024
seconds (JVM running...
2017-12-16 23:18:56.346 : Closing
org.springframework.context.annotation.AnnotationC..
2017-12-16 23:18:56.347 : Unregistering JMX-exposed beans on
shutdown
2017-12-16 23:18:56.349 : Closing JPA EntityManagerFactory for
persistence unit 'def...
2017-12-16 23:18:56.349 : HHH000227: Running hbm2ddl schema
export
2017-12-16 23:18:56.350 : HHH000230: Schema export complete BUILD SUCCESSFUL Total time: 52.323 secs

How it works...

As we can see, the application started just fine, but as we didn't add any functionality or configure any services, it existed straight away. From the startup log, however, we do see that the autoconfiguration did take place. Let's take a look at the following lines:

    Building JPA container EntityManagerFactory for persistence unit 
'default'
HHH000412: Hibernate Core {5.2.12.Final} HHH000400: Using dialect: org.hibernate.dialect.H2Dialect

This information tells us that, because we added the jdbc and data-jpa starters, the JPA container was created and will use Hibernate 5.2.12.Final to manage the persistence using H2Dialect. This was possible because we had the right classes in the classpath.

Using the command-line runners

With our basic application skeleton ready, let's add some meat to the bones by making our application do something.

Let's start by first creating a class named StartupRunner. This will implement the CommandLineRunner interface, which basically provides just one method: public void run(String... args) --that will get called by Spring Boot only once after the application has started.

How to do it...

  1. Create the file named StartupRunner.java under the src/main/java/com/example/bookpub/ directory from the root of our project with the following content:
        package com.example.bookpub; 

import com.example.bookpub.repository.BookRepository; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;

public class StartupRunner implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("Hello"); }
}
  1. After we have defined the class, let's proceed by defining it as @Bean in the BookPubApplication.java application configuration, which is located in the same folder as our newly created StartupRunner.java file as follows:
@Bean 
public StartupRunner schedulerRunner() { 
    return new StartupRunner(); 
} 

How it works...

If we run our application again, by executing $ ./gradlew clean bootRun, we will get an output that is similar to the previous one. However, we will see our Hello message in the logs as well, which is as follows:

2017-12-16 21:57:51.048  INFO --- 
com.example.bookpub.StartupRunner : Hello

Even though the program will get terminated on execution, at least we made it do something!

Command-line runners are a useful functionality to execute the various types of code that only have to be run once, after startup. Some also use this as a place to start various executor threads, but Spring Boot provides a better solution for this task, which will be discussed at the end of this chapter. The command-line runner interface is used by Spring Boot to scan all of its implementations and invoke each instance's run method with the startup arguments. We can also use an @Order annotation or implement an Ordered interface so as to define the exact order in which we want Spring Boot to execute them. For example, Spring Batch relies on the runners to trigger the execution of the jobs.

As the command-line runners are instantiated and executed after the application has started, we can use the dependency injection to our advantage to wire in whatever dependencies we need, such as datasources, services, and other components. These can be utilized later while implementing run.

It is important to note that if any exception is thrown in the run(String... args) method, this will cause the context to close and an application to shut down. Wrapping the risky code blocks with try/catch is recommended to prevent this from happening.

Setting up a database connection

In every application, there is a need to access some data and conduct some operations on it. Most frequently, this source of data is a datastore of some kind, namely a database. Spring Boot makes it very easy to get started in order to connect to the database and start consuming the data via the JPA, among others.

Getting ready

In our previous example, we created the basic application that will execute a command-line runner by printing a message in the logs. Let's enhance this application by adding a connection to a database.

Earlier, we already added the necessary jdbc and data-jpa starters as well as an H2 database dependency to our build file. Now we will configure an in-memory instance of the H2 database.

In the case of an embedded database, such as H2, Hyper SQL Database (HSQLDB), or Derby, no actual configuration is required besides including the dependency on one of these in the build file. When one of these databases is detected in the classpath and a DataSource bean dependency is declared in the code, Spring Boot will automatically create one for you.

To demonstrate the fact that just by including the H2 dependency in the classpath, we will automatically get a default database, let's modify our StartupRunner.java file to look as follows:

public class StartupRunner implements CommandLineRunner { 
    protected final Log logger = LogFactory.getLog(getClass()); 
    @Autowired 
    private DataSource ds; 
    @Override 
    public void run(String... args) throws Exception { 
        logger.info("DataSource: "+ds.toString()); 
    } 
} 

Now, if we proceed with the running of our application, we will see the name of the datasource printed in the log, as follows:

2017-12-16 21:46:22.067 com.example.bookpub.StartupRunner   
:DataSource: org.apache.tomcat.jdbc.pool.DataSource@4... {...driverClassName=org.h2.Driver; ... }

So, under the hood, Spring Boot recognized that we've autowired a DataSource bean dependency and automatically created one initializing the in-memory H2 datastore. This is all well and good, but probably not all too useful beyond an early prototyping phase or for the purpose of testing. Who would want a database that goes away with all the data as soon as your application shuts down and you have to start with a clean slate every time you restart the application?

How to do it...

Let's change the defaults in order to create an embedded H2 database that will not store data in-memory, but rather use a file to persist the data among application restarts, by performing the following steps:

  1. Open the file named application.properties under the src/main/resources directory from the root of our project and add the following content:
spring.datasource.url = jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 
spring.datasource.username = sa 
spring.datasource.password = 
  1. Start the application by executing ./gradlew clean bootRun from the command line
  2. Check your home directory, and you should see the following file in there: test.mv.db
The user home directory is located under /home/<username> on Linux and under /Users/<username> on macOS X.

How it works...

Even though, by default, Spring Boot makes certain assumptions about the database configuration by examining the classpath for the presence of supported database drivers, it provides you with easy configuration options to tweak the database access via a set of exposed properties grouped under spring.datasource.

The things that we can configure are url, username, password, driver-class-name, and so on. If you want to consume the datasource from a JNDI location, where an outside container creates it, you can configure this using the spring.datasource.jndi-name property. The complete set of possible properties is fairly large, so we will not go into all of them. However, we will cover more options in Chapter 5, Application Testing, where we will talk about mocking data for application tests using a database.

By looking at various blogs and examples, you may notice that some places use dashes in property names like driver-class-name, while others use camel-cased variants: driverClassName. In Spring Boot, these are actually two equally supported ways of naming the same property, and they get translated into the same thing internally.

If you want to connect to a regular (non-embedded) database, besides just having the appropriate driver library in the classpath, we need to specify the driver of our choice in the configuration. The following code snippet is what the configuration to connect to MySQL would resemble:

    spring.datasource.driver-class-name: com.mysql.jdbc.Driver
    spring.datasource.url:   
jdbc:mysql://localhost:3306/springbootcookbook
spring.datasource.username: root spring.datasource.password:

If we wanted Hibernate to create the schema automatically, based on our entity classes, we would need to add the following line to the configuration:

    spring.jpa.hibernate.ddl-auto=create-drop
  
Don't do it in the production environment, otherwise, on startup, all the table schemas and data will be deleted! Use the update or validate values instead, where needed.

You can go even further in the abstraction layer and, instead of autowiring a DataSource object, you could go straight for JdbcTemplate. This would instruct Spring Boot to automatically create a DataSource and then create a JdbcTemplate wrapping the datasource, thus providing you with a more convenient way of interacting with a database in a safe way. The code for JdbcTemplate is as follows:

@Autowired 
private JdbcTemplate jdbcTemplate; 

You can also look in the spring-boot-autoconfigure source at an org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration file to see the code behind the datasource creation magic.

Setting up a data repository service

Connecting to a database and then executing good old SQL, though simplistic and straightforward, is not the most convenient way to operate on the data, map it in a set of domain objects, and manipulate the relational content. This is why multiple frameworks emerged to aid you with mapping the data from tables to objects, better known as object-relational mapping (ORM). The most notable example of such a framework is Hibernate.

In the previous example, we covered how to set up a connection to a database and configure the settings for the username and password, and we also discussed which driver to use, and so on. In this recipe, we will enhance our application by adding a few entity objects that define the structure of the data in the database and a CrudRepository interface to access the data.

As our application is a book-tracking catalogue, the obvious domain objects would be Book, Author, Reviewers, and Publisher.

How to do it...

  1. Create a new package folder named entity under the src/main/java/com/example/bookpub directory from the root of our project.
  2. In this newly created package, create a new class named Book with the following content:
@Entity 
public class Book { 
  @Id 
  @GeneratedValue 
  private Long id; 
  private String isbn; 
  private String title; 
  private String description; 
 
  @ManyToOne 
  private Author author; 
  @ManyToOne 
  private Publisher publisher; 
 
  @ManyToMany 
  private List<Reviewers> reviewers; 
 
  protected Book() {} 
 
  public Book(String isbn, String title, Author author, 
Publisher publisher) { this.isbn = isbn; this.title = title; this.author = author; this.publisher = publisher; } //Skipping getters and setters to save space, but we do need them }
  1. As any book should have an author and a publisher, and ideally some reviewers, we need to create these entity objects as well. Let's start by creating an Author entity class, under the same directory as our Book, as follows:
@Entity 
public class Author { 
  @Id 
  @GeneratedValue 
  private Long id; 
  private String firstName; 
  private String lastName; 
  @OneToMany(mappedBy = "author") 
  private List<Book> books; 
 
  protected Author() {} 
 
  public Author(String firstName, String lastName) {...} 
    //Skipping implementation to save space, but we do need 
it all }
  1. Similarly, we will create the Publisher and Reviewer classes, as shown in the following code:
@Entity 
public class Publisher { 
  @Id 
  @GeneratedValue 
  private Long id; 
  private String name; 
  @OneToMany(mappedBy = "publisher") 
  private List<Book> books; 
 
  protected Publisher() {} 
 
  public Publisher(String name) {...} 
} 
 
@Entity 
public class Reviewer { 
  @Id 
  @GeneratedValue 
  private Long id; 
  private String firstName; 
  private String lastName; 
 
  protected Reviewer() {} 
 
  public Reviewer(String firstName, String lastName) 
{...}
}
  1. Now we will create our BookRepository interface by extending Spring's CrudRepository interface under the src/main/java/com/example/bookpub/repository package, as follows:
@Repository 
public interface BookRepository 
extends CrudRepository<Book, Long> { public Book findBookByIsbn(String isbn); }
  1. Finally, let's modify our StartupRunner class in order to print the number of books in our collection, instead of some random datasource string, by autowiring a newly created BookRepository and printing the result of a .count() call to the log, as follows:
public class StartupRunner implements CommandLineRunner { 
  @Autowired private BookRepository bookRepository; 
 
  public void run(String... args) throws Exception { 
    logger.info("Number of books: " + 
bookRepository.count()); } }

How it works...

As you have probably noticed, we didn't write a single line of SQL, or even mention anything about database connections, building queries, or things like that. The only hint about the fact that we are dealing with the database-backed data in our code is the presence of class and field annotations: @Entity, @Repository, @Id, @GeneratedValue, and @ManyToOne, along with @ManyToMany and @OneToMany. These annotations, which are a part of the JPA, along with the extension of the CrudRepository interface, are our ways of communicating with Spring about the need to map our objects to the appropriate tables and fields in the database and provide us with the programmatic ability to interact with this data.

Let's go through the following annotations:

  • @Entity indicates that the annotated class should be mapped to a database table. The name of the table will be derived from the name of the class, but it can be configured, if needed. It is important to note that every entity class should have a default protected constructor, which is needed for automated instantiation and Hibernate interactions.
  • @Repository indicates that the interface is intended to provide you with the access and manipulation of data for a database. It also serves as an indication to Spring during the component scan that this instance should be created as a bean that will be available for use and injection into other beans in the application.
  • The CrudRepository interface defines the basic common methods to read, create, update, and delete data from a data repository. The extra methods that we will define in our BookRepository extension, public Book findBookByIsbn(String isbn), indicate that Spring JPA should map the call to this method to a SQL query selecting a book by its ISBN field. This is a convention-named mapping that translates the method name into a SQL query. It can be a very powerful ally, allowing you to build queries, such as findByNameIgnoringCase(String name) and others.
  • The @Id and @GeneratedValue annotations provide you with an indication that an annotated field should be mapped to a primary key column in the database and that the value for this field should be generated, instead of being explicitly entered.
  • The @ManyToOne and @ManyToMany annotations define the relational field associations that refer to the data stored in the other tables. In our case, multiple books belong to one author, and many reviewers review multiple books.
  • The mappedBy attribute in the @OneToMay annotation defines a reverse association mapping. It indicates to Hibernate that the mapping source of truth is defined in the Book class, in the author or publisher fields.
For more information about all the vast capabilities of Spring Data, visit http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/.

Scheduling executors

Earlier in this chapter, we discussed how the command-line runners can be used as a place to start the scheduled executor thread pools to run the worker threads in intervals. While that is certainly a possibility, Spring provides you with a more concise configuration to achieve the same goal: @EnableScheduling.

Getting ready

We will enhance our application so that it will print a count of books in our repository every 10 seconds. To achieve this, we will make the necessary modifications to the BookPubApplication and StartupRunner classes.

How to do it...

  1. Let's add an @EnableScheduling annotation to the BookPubApplication class, as follows:
@SpringBootApplication 
@EnableScheduling 
public class BookPubApplication {...}
  1. As a @Scheduled annotation can be placed only on methods without arguments, let's add a new run() method to the StartupRunner class and annotate it with the @Scheduled annotation, as shown in the following line:
@Scheduled(initialDelay = 1000, fixedRate = 10000) 
public void run() { 
    logger.info("Number of books: " +  
        bookRepository.count()); 
} 
  1. Start the application by executing ./gradlew clean bootRun from the command line so as to observe the Number of books: 0 message that shows in the logs every 10 seconds.

How it works...

@EnableScheduling, as many other annotations that we have discussed and will discuss in this book, is not a Spring Boot; it is a Spring Context module annotation. Similar to the @SpringBootApplication and @EnableAutoConfiguration annotations, this is a meta-annotation and internally imports SchedulingConfiguration via the @Import(SchedulingConfiguration.class) instruction, which can be found inside ScheduledAnnotationBeanPostProcessor that will be created by the imported configuration and will scan the declared Spring beans for the presence of the @Scheduled annotations. For every annotated method without arguments, the appropriate executor thread pool will be created. It will manage the scheduled invocation of the annotated method.

Left arrow icon Right arrow icon

Key benefits

  • • This collection of effective recipes serves as guidelines for Spring Boot application development
  • • Get up to date with features of the latest version of Spring Boot 2.0
  • • Tips and tricks to improve your efficiency through the stages of software development

Description

The Spring framework provides great flexibility for Java development, which also results in tedious configuration work. Spring Boot addresses the configuration difficulties of Spring and makes it easy to create standalone, production-grade Spring-based applications. This practical guide makes the existing development process more efficient. Spring Boot Cookbook 2.0 Second Edition smartly combines all the skills and expertise to efficiently develop, test, deploy, and monitor applications using Spring Boot on premise and in the cloud. We start with an overview of the important Spring Boot features you will learn to create a web application for a RESTful service. Learn to fine-tune the behavior of a web application by learning about custom routes and asset paths and how to modify routing patterns. Address the requirements of a complex enterprise application and cover the creation of custom Spring Boot starters. This book also includes examples of the new and improved facilities available to create various kinds of tests introduced in Spring Boot 1.4 and 2.0, and gain insights into Spring Boot DevTools. Explore the basics of Spring Boot Cloud modules and various Cloud starters to make applications in “Cloud Native” and take advantage of Service Discovery and Circuit Breakers.

Who is this book for?

This book is for Java Developers who have good knowledge and understanding of Spring and Java application development.

What you will learn

  • • Get to know Spring Boot Starters and create custom auto-configurations
  • • Work with custom annotations that enable bean activation
  • • Use DevTools to easily develop and debug applications
  • • Learn the effective testing techniques by integrating Cucumber and Spock
  • • Observe an eternal application configuration using Consul
  • • Move your existing Spring Boot applications to the cloud
  • • Use Hashicorp Consul and Netflix Eureka for dynamic Service Discovery
  • • Understand the various mechanisms that Spring Boot provides to examine an application's health

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 26, 2018
Length: 286 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787123670
Vendor :
Pivotal
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 26, 2018
Length: 286 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787123670
Vendor :
Pivotal
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
Learning Spring Boot 2.0
€36.99
Spring 5.0 By Example
€36.99
Spring Boot 2.0 Cookbook
€36.99
Total 110.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Getting Started with Spring Boot Chevron down icon Chevron up icon
Configuring Web Applications Chevron down icon Chevron up icon
Web Framework Behavior Tuning Chevron down icon Chevron up icon
Writing Custom Spring Boot Starters Chevron down icon Chevron up icon
Application Testing Chevron down icon Chevron up icon
Application Packaging and Deployment Chevron down icon Chevron up icon
Health Monitoring and Data Visualization Chevron down icon Chevron up icon
Spring Boot DevTools Chevron down icon Chevron up icon
Spring Cloud Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(3 Ratings)
5 star 0%
4 star 33.3%
3 star 0%
2 star 0%
1 star 66.7%
Amazon Customer Mar 20, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Very helpful book. Concepts explained very well. One should really refer the book to have concepts clear. One to recommend.
Amazon Verified review Amazon
Sanjay Kumar J Aug 23, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Not for professionals
Amazon Verified review Amazon
Keith Lancaster Jun 16, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I can't tell you anything about the book, since I download the Kindle preview to check it out and it STOPS at the table of contents! NO sample text.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.