The authors take advantage of less complex alternatives whenever possible, and shows how Spring can make you more productive in compli Professional Java Development with the Spring Framework.
This book shows you not only what Spring can do but why, explaining its functionality and motivation to help you use all parts of the framework to develop successful applications. You will be guided through all the Spring features and see how they form a coherent whole. In turn, this will help you understand the rationale for Spring's approach, when to use Spring, and how to follow best practices. All this is illustrated with a complete sample application.
When you finish the book, you will be well equipped to use Spring effectively in everything from simple Web applications to complex enterprise applications. Beginning Zend Framework. Beginning Zend Framework is a beginners guide to learning and using the Zend Framework. It covers everything from the installation to the various features of the framework to get the reader up and running quickly.
Persistence with Spring and Spring Data. Spring Security. Next Steps. Back Matter Pages About this book Introduction Get started with Spring Framework 5 and its ecosystem, with a guide to the working practices in modern development.
This book will teach you how to use the Spring Framework to build Java-based applications, web applications, and microservices. Beginning Spring 5 discusses how you can build apps with the Spring mindset and what the benefits of that mindset are. Along the way you will learn many aspects of the Spring ecosystem with easy-to-understand applications designed to teach you not only the technology, but also the practices that benefit the most from Spring.
Discover the most common use cases encountered in the real world Create reliable, tested, modular software, building skills that will translate well across all languages and environments. Spring 5 Spring Framework Spring Framework 5 Beginning practical projects code source pragmatic in-depth tutorial introduction learn Java. Authors and affiliations Joseph B. Ottinger 1 Andrew Lombardi 2 1.
You have created the JUnit test class to test for PostService methods. You are performing various operations and asserting the response based on the same data you inserted using data. Assuming you have generated code using the H2 profile, you can run the JUnit test without any further configuration. But if you have generated code using the mysql profile, you will have to configure the following properties in application. JPA simplifies the implementation of the data access layer by letting developers work with an object oriented API instead of writing SQL queries by hand.
You can also use Spring's declarative transaction management capabilities with JPA. This chapter explores the Spring Data JPA, explains how to use it with Spring Boot, and looks into how you can work with multiple databases in the same Spring Boot application. At times, you may need to implement the data management applications to store, edit, and delete data. They provide out-of-the-box support for CRUD operations, as well as pagination and sorting. See Figure Siva Prasad Reddy 83 K.
As shown in Figure, JpaRepository provides several methods for CRUD operations, along with the following interesting methods: long count ;Returns the total number of entities available. But sometimes you may not be able to express your criteria using method names or the method names look ugly.
Spring Data provides flexibility to configure the query explicitly using the Query annotation. Query "select u from User u where u. Modifying Query "update User u set u. Note that this example uses the named parameter :status instead of the positional parameter? Create a Spring Boot Maven project and add the following dependencies. Create a user JPA entity, as shown in Listing JPA Entity User. Create the UserRepository interface by extending the JpaRepository interface, as shown in Listing Since you configured the in-memory database H2 driver, Spring Boot automatically registers a DataSource.
Add Dynamic Query Methods Now youll add some finder methods to see how dynamic query generation based on method names works. To get a user by name, use this:. The preceding method generates a where clause like where u. Suppose you want to do a wildcard search, such as where u. You can use Query as follows:. Using the Sort and Pagination Features Suppose you want to getall users by their names in ascending order. You can use the findAll Sort sort method as follows:.
The users will be ordered first by name in ascending order and then by ID in descending order. In many web applications, youll want to show data in a page-by-page manner. Spring Data makes it very easy to load data in the pagination style. Suppose you want to load the first 25 users on one page. We can use Pageable and PageRequest to get results by page, as follows:. The usersPage will contain the first 25 user records only.
You can get additional details, like the total number of pages, the current page number, whether there is a next page, whether there is a previous page, and more. Working with Multiple Databases Spring Boot autoconfiguration works out-of-the-box if you have single database to work with and provides plenty of customization options through its properties.
But if your application demands more control over the application configuration, you can turn off specific autoconfigurations and configure the components by yourself. For example, you might want to use multiple databases in the same application. If you add the spring-boot-starter-data-jpa starter and just define the DataSource beans only, then Spring Boot will try to automatically create some beans for example, TransactionManager , assuming there will be only one data source.
It will fail. Create a Spring Boot application with the data-jpa starter. Configure the following dependencies in pom. As you have turned off AutoConfigurations, you are enabling TransactionManagement explicitly by using the EnableTransactionManagement annotation. Configure the datasource properties. Configure the Security and Orders database connection parameters in the application. Driver datasource. Here, you have used custom property keys to configure the two datasource properties.
Then create a User entity, as follows:. AUTO private Integer id;. Note that you have created User. Create an Order entity as follows:. Note that you have created Order. Create SQL scripts to initialize sample data. Create the security-data. Create the orders-data.
Create the SecurityDBConfig. Observe that you have populated the datasource. You have configured the DataSourceInitializer bean to initialize the sample data from security-data. You also configured the basePackages property to indicate where to look for the Spring Data JPA repositories the packages. Create the OrdersDBConfig. Similar to SecurityDBConfig.
Note that you have used datasource. Spring Boot provides a starter for Spring Data Mongo, which makes it even easier to use by implementing its autoconfiguring mechanism. The chapter explains how to perform various database operations from the Mongo Shell. Then you will explore how to use Spring Data Mongo features by using Spring Boot's spring-boot-starter-data-mongodb starter.
MongoDB stores documents in collections. Collections are analogous to tables in relational databases. Unlike a table, however, a collection does not require its documents to have the same schema. Siva Prasad Reddy 99 K. MongoDB requires a data directory to store its files. After you run this command, MongoDB should start on default port Instead of running this command and passing all the configuration options every time, you can create a config file and batch script to start MongoDB.
For example, you could create mongod. You create start-mongo. Once Homebrew is installed, you need to update Homebrew's package database and install the MongoDB package as follows:. Make sure that the data directory has read-write permission. You can start the Mongo server without specifying the dbpath, which means it will use the default data directory, or you can pass a custom data directory location as follows:.
If you have connected to the server successfully, it will print the MongoDB Shell version and the message connecting to: test. For interactive help, type "help". By default, you are connected to the default database called test. If the collection does not exist, it will be created automatically. You can query the database to return all the documents as follows:. Note Covering MongoDB in-depth is out of the scope of this book.
Spring Boot provides the spring-boot-starter-data-mongodb starter to easily work with MongoDB by autoconfiguring the MongoDB components without requiring the manual configuration. You can customize the mongodb server URL by configuring the spring. You can also use MongoTemplate to save, update, and delete domain objects that internally take care of mapping domain objects to documents in MongoDB. First, you create the User class as follows:.
In addition to using MongoTemplate, you can also create repositories that extend the MongoRepository interface and provide CRUD operations out-of-the-box.
You can map a domain object to a particular MongoDB collection name using the Document annotation. But you can map any existing property to be used as the primary key, simply by using the Id annotation. Create the UserRepository interface by extending the MongoRepository interface, as shown in Listing Using Embedded Mongo for Testing It would be more convenient to use an embedded MongoDB for testing purposes, especially in continuous integration environments.
You can also initialize sample data by implementing the CommandLineRunner interface, which executes the public void run String args method upon application startup, as shown in Listing Override public void run String Summary This chapter explained how to install and use the MongoDB server.
Since the Spring 3. Traditionally JSPs are being used for view rendering, but there are many other view templating technologies emerged over the time such as Thymeleaf, Mustache, Groovy Templates, FreeMarker, etc. Spring Boot provides autoconfiguration for these view templating libraries as well. Spring Boot provides embedded servlet container support so that you can build your applications as self-contained deployment units.
Spring Boot supports Tomcat, Jetty, and Undertow servlet containers out- of-the-box and provides customization hooks to implement all server level customizations. This chapter looks into how to develop Spring MVC based web applications using the Web starter with Tomcat, Jetty, and Undertow as embedded servlet containers. You will learn how to customize the default Spring MVC configuration and how to register servlets, filters, and listeners as Spring beans.
You will learn how to use Thymeleaf View templates, how to perform form validations, and how to upload files and use ResourceBundles for internationalization i18n.
Finally, you will learn about various ways of handling exceptions using ExceptionHandler and ControllerAdvice annotations and how Spring Boot makes it even simpler to do so. Spring MVC provides DispatcherServlet, which acts as a front controller by receiving all the requests and delegates the processing to request handlers controllers. Once the processing is done, ViewResolver will render a view based on the view name. Figure shows this flow process. Siva Prasad Reddy K.
Resolve view using 2 View Resolver 3. Spring 4. Spring Boot provides the Web starter, which autoconfigures all these commonly used web layer components, thus making web application development much easier. You can develop a Spring Boot web application as a JAR type module using an embedded servlet container or as a WAR type module, which can be deployed on any external servlet container. You can override the static resource locations by configuring the spring. Copy an image, such as spring-boot.
Create the index. Use the Bootstrap navigation bar component. You should be able to see the web page with the Bootstrap navigation bar, as shown in Figure By default, the Spring Boot Web starter uses Tomcat as the embedded servlet container and runs on port However, you can customize the server properties using server. So, you would access the index. Instead of Tomcat, though, you can use other servlet containers like Jetty or Undertow.
To use Jetty as the embedded container, you simply need to exclude spring-boot-starter-tomcat and add spring-boot-starter-jetty.
Spring Boot provides autoconfiguration support for the Undertow server as well. Similar to what you saw with Jetty, you can configure Spring Boot to use the Undertow embedded server instead of Tomcat as follows:.
You can customize various properties of the Tomcat, Jetty, and Undertow servlet containers using the server. If not specified a temporary directory will be used.
If not specified, logs will be redirected to "System. Use the org. ServerProperties class to see a complete list of server customization properties. Customizing Embedded Servlet Containers Spring Boot provides lot of customization options for configuring servlet containers using the server. You can customize the port, connectionTimeout, contextPath, and SSL configuration parameters, as well as the session configuration parameters by configuring these properties in application.
First, you generate a self-signed SSL certificate using the following command:. After providing answers to questions that keytool asks, it will generate a KeyStore. Now configure the SSL properties in the application.
If you are using the Tomcat embedded container, you can register TomcatServletWebServerFactory programmatically, as shown in Listing Http11NioProtocol" ; connector.
Customizing SpringMVC Configuration Most of the time, Spring Boots default autoconfiguration, along with the customization properties, will be sufficient to tune your web application. But at times, you may need more control to configure the application components in a specific way to meet your application needs. If you want to take advantage of Spring Boots autoconfiguration and add some additional MVC configuration interceptors, formatters, view controllers, etc.
Suppose you created the servlet shown in Listing and marked it as a Spring bean using the Component annotation. With this approach, you can take advantage of Springs dependency injection for servlets, filters, and listeners. Lets take a look at how you can register filters and listeners as well.
JavaMelody can provide various metrics about the running application, including: A summary indicating the overall number of executions, the average execution time, the CPU time, and the percentage of errors.
The percentage of time spent on the requests when the average time exceeds a configurable threshold. The complete list of requests, aggregated without dynamic parameters with the number of executions, the mean execution time, the mean CPU time, the percentage of errors, and an evolution chart of execution time over time.
Integrating JavaMelody into a Java web application is very simple. You need to register net. MonitoringFilter, which is a filter, and net. SessionListener, which is a HttpSessionListener. The first thing you do if you want to build a deployable WAR file is change the packaging type. If you are using Maven, then in pom. When you add the spring-boot-starter-web dependency. It will transitively add the spring-boot- starter-tomcat dependency as well.
So you need to add spring-boot-starter-tomcat as the provided scope so that it wont get packaged inside the WAR file. If you are using Gradle, add spring-boot-starter-tomcat with the providedRuntime scope as follows:. Finally, you need to provide a SpringBootServletInitializer sub-class and override its configure method. You can simply make your applications entry point class extend SpringBootServletInitializer, as shown in Listing However, there are new view templating libraries, such as Thymeleaf, Mustache, etc.
Spring Boot provides autoconfiguration for the following view templating technologies. Among the supporting view templates, Thymeleaf is the most popular one used in Spring Boot applications. In this section, you see how you can use Thymeleaf in a Spring Boot web application. Create a Spring Boot Maven project with the spring-boot-starter-thymeleaf starter. Create the Thymeleaf view called home.
Now run the following entry point class. Create the registration. You are adding the User object to Model with the "user" key so that you can bind the form properties in your Thymeleaf form. Note that this example uses two Thymeleaf attributesth:action builds a context-relative URL and th:object specifies the model attribute name.
Form Validation Validating the user submitted data is crucial in web applications. First, you need to specify the user validation rules using Java Bean validation annotations. Thymeleaf provides the syntax fields. You can use fields. You can now update registration. The registration. With this updated form if there are any form validation failures, it will show those errors next to the field and all global errors at the beginning.
You can add the Valid annotation to the model parameter to perform validations on the form submit. You also need to define the BindingResult parameter immediately next to the model object. The validation errors will be populated in BindingResult, which you can inspect later in your method body.
When the form is submitted with invalid data, those validation errors will be populated in BindingResult. The example checks whether there are any errors and redisplays the registration form, which will be rendered along with the errors.
Sometimes you cant express all the validation rules using annotations only. For example, you want the user e-mail to be unique. You cant implement this without checking against your database. Next, youll see how you can use Springs Validation framework to implement complex validations. You can create UserValidator by implementing the org. Validator interface, as shown in Listing In the validate Object target, Errors errors method, you can implement any complex validation logic and register errors.
Now you can inject UserValidator into the RegistrationController and use it to validate the model object as follows:. When the form is then submitted, if there are any validation failures as per the Bean Validation Constraint annotations, they will be populated in BindingResult. After that, the example checks for duplicate e-mails using userValidator. This will add an error to the email property if the given e-mail already exists. File Uploading Spring Boots org. MultipartAutoConfiguration enables multi-part uploads by default.
You can then implement the FileUploadController to handle the request, as shown in Listing Note that this example binds the file type input parameter myFile to the MultipartFile argument with RequestParam "myFile" , from which you can extract byte[] or InputStream.
You can customize multipart configuration using the following properties:. You can add ResourceBundles such as messages. You can also customize the ResourceBundles basename using the spring. In addition to that, Spring Boot provides the following customization properties.
If set to -1, bundles are cached forever spring. Create the default ResourceBundle messages. You can also obtain these messages programmatically from MessageSource, as shown in Listing By default, Hibernate validation looks for the ValidationMessages.
If you want to use messages. Autowired private MessageSource messageSource;. Error Handling You can handle exceptions in Spring MVC applications by registering the SimpleMappingExceptionResolver bean and configuring which view to render for what type of exception, as shown in Listing You can also use the ExceptionHandler annotation to define handler methods for specific exception types, as shown in Listing You can handle exceptions globally by creating an exception handler class annotated with ControllerAdvice.
The ExceptionHandler methods in the ControllerAdvice class handle errors that occur in any controller request handling method. ExceptionHandler DataAccessException. You can provide the custom error page by implementing ErrorController. You can also provide custom error pages based on the HTTP error status code. Summary This chapter discussed how to develop web applications using Spring Boot with Thymeleaf view templates. You learned how to handle exception scenarios at the controller level and globally.
REST REpresentational State Transfer is an architectural style for building distributed systems that provide interoperability between heterogeneous systems. For web-based systems, HTTP is the most commonly used protocol for communicating with external systems.
You can identify a unique resource using a URI. A resource can be a collection resource, which represents a grouped set of resources. The resources that can be identified in a blog domain are post, comment, and user. The typical practice of determining the input request content and output response types in web based systems are based on the ContentType and Accept header values. It just looks like a normal SpringMVC controller, with two noticeable differences: Unlike the normal controller methods, which return a view name or a ModelAndView object, the listPosts method returns a list of Post objects.
The listPosts request handler method is annotated with ResponseBody. The ResponseBody annotation on the request handler method indicates that the return value should be bound to the response body.
Listing shows another method used to create a new post. In the createPost handler method, the interesting part is the RequestBody annotation.
The RequestBody annotation will take care of binding the web request body to the method parameter with the help of the registered HttpMessageConverters. If all of your handler methods are REST endpoint handler methods, you can have a ResponseBody at the class level instead of adding it to each method. Even better, you can use RestController, which is a composed annotation of Controller and ResponseBody. Create a Spring Boot Maven project and add the following starters:. Model the REST resources.
This example assumes your blog application is a simple one where the administrator can create posts, and the blog viewers can view and add their comments to the posts. You can therefore identify that there will be User, Post, and Comment resources in the application domain. First, you create these resources as JPA entities, as shown in Listing JPA Entities User. Temporal TemporalType. It will be thrown when the client sends a request to get the details of a resource that doesnt exist.
Youll start by implementing the endpoint for creating a new post. ResponseStatus HttpStatus. So, you are annotating with ResponseStatus HttpStatus. This example is loading all the posts from the database and returning them as a response. The example gets the Post object from the database for the given ID and throws the ResourceNotFoundException if the post not found, otherwise updating the post. Note that you are not returning any content to the client, so on successful deletion of the post, the HTTP OK status code will be sent.
You can also implement the REST endpoints for creating new comments and deleting an existing comment for a given post as follows:.
This example adds the Valid annotation to the method parameter Post so that the post object data will be validated against the Java Bean Validation Constraints defined on the POST properties. Otherwise, it saves the post and adds custom response headers. First, you need to populate some sample data using the SQL script, as shown in Listing Now youll write a Spring Boot test that starts an embedded servlet container on a defined port server.
You then received the responses as Java objects using the HttpMessageConverters. Now youll see how you can enable CORS support on a specific request handling method. All headers and origins are permitted Credentials are allowed Maximum age is set to 30 minutes The list of HTTP methods is set to the methods on the RequestMethod annotation.
GET, RequestMethod. When applied at the class level, the same CrossOrigin configuration is applied to all the RequestMapping methods. If the CrossOrigin annotation is specified at both the class level and the method level, Spring will derive the CORS configuration by combining attributes from both annotations. Assume you have the following Post and Comment entities:. Here, you have a bi-directional association between the Post and Comment entities.
You can fix the infinite recursion problem by using the Jackson JSON library annotations in the following ways. Using JsonIgnore You can break the infinite recursion by adding the JsonIgnore annotation on the back reference from the child object. You can add JsonIgnore on all the properties that you want to exclude from marshaling or you can use JsonIgnoreProperties at the class level to list all the property names to ignore.
Note The JsonManagedReference annotation is used to indicate that the annotated property is part of a two-way linkage between fields and that its role is as a "parent" or "forward" link. The JsonBackReference annotation is also used to indicate that the associated property is part of a two-way linkage between fields, but its role is as a "child" or "back" link.
At times, you may need more control over the response formats and cant or dont want to directly expose database entities as REST endpoint responses. To expose the Spring Data repositories as REST resources with the defaults, you dont need to add any extra configuration. Now you can run the following entry point class to start the server. This should return the response shown in Listing You can customize the path using the spring. You can use the size query parameter to limit the number of entries returning.
To retrieve the second page entries with five entries per page, use the page and size query parameters. Spring Data REST by default exposes all the public repository interfaces without requiring any extra configuration. But if you want to customize the defaults, you can use the RepositoryRestResource and RestResource annotations. You can also customize the default path and rel attribute values using RepositoryRestResource, as follows:.
For example, by default, the entitys primary key id values wont be exposed in the responses. If you want to expose the id values for certain entities, you can customize it as follows:. Instead of rendering a view, you can return ResponseEntity with the appropriate HTTP status code and exception details.
Instead of simply throwing an exception with the HTTP status code, it is better to provide more details about the issue, such as the error code, message, developer message, etc. In the controller handler method, you can throw exception based on error conditions and handle those exceptions using the ExceptionHandler methods, as shown in Listing ExceptionHandler PostDeletionException. You can handle exceptions globally using the ControllerAdvice class with the ExceptionHandler methods, as shown in Listing ExceptionHandler Exception.
The global exception handling mechanism helps you handle exceptions like database communication errors and third-party service invocation failures in a central place instead of handling them in each controller class.
It also looked at how to handle exceptions at the controller level and globally. Modern IT business needs have changed significantly compared to a few years ago. The amount of data that is being generated from various sources like social media sites, IoT devices, sensors, and the like is humongous.
The traditional data processing models may not be suitable to process such a huge volume of data. Even though we have better hardware support these days, many of the existing APIs are synchronous and blocking APIs, which become bottlenecks to better throughput.
Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming is gaining momentum and many of the programming languages provide reactive frameworks and libraries. In Java, there are reactive libraries like RxJava and Reactor, which supports reactive programming. As interest in reactive programming grows in the Java community, a new initiative called reactive streams is starting to provide a standard for asynchronous stream processing with non-blocking back pressure.
Reactive streams support will be part of the Java 9 release. The Spring framework 5 introduced support for reactive programming with the new WebFlux module.
Spring Boot 2, which uses Spring 5, also provides a starter to quickly create reactive applications using WebFlux. This chapter teaches you how to build reactive web applications using Spring WebFlux. Introduction to Reactive Programming Reactive programming involves modeling data and events as observable data streams and implementing data processing routines to react to the changes in those streams.
Reactive programming is becoming popular and there are already reactive frameworks or libraries for many of the popular programming languages.
The key components of reactive streams are the Publisher and Subscriber. A Publisher is a provider of an unbounded number of sequenced elements, which are published according to the demand received from the subscriber s. A Subscriber subscribes to the publisher for callbacks. Publishers dont automatically push data to subscribers unless subscribers request the data.
Project Reactor Project Reactor is an implementation of the reactive streams specification with non-blocking and back pressure support. Reactor provides two composable reactive typesFlux and Monothat implement the publisher but also provide a rich set of operators. A Flux represents a reactive sequence of N items, whereas a Mono represents a single value or an empty result.
Now youll see how to create Mono and Flux types and how to consume data from them. Until you subscribe to the publisher, no data flow will happen. You must enable logging and subscribe to the flux. Looking at the log statements, you can see that when you subscribe to Publisher: The onSubscribe method is called when you subscribe to Publisher Flux.
When you call subscribe on Publisher, a subscription is created. This subscription requests data from the publisher. In this example, it defaults to unbounded and hence it requests every element available. The onNext callback method is called for every element. The onComplete callback method is called last after receiving the last element.
If an error occurs while consuming the next element, then onError callback would have been called. Note Covering Project Reactor in-depth is out of the scope of this book. The Spring WebFlux Reactive framework is built on top of Project Reactor, which is an implementation of the reactive streams specification. Reactive Web Applications Using Spring WebFlux Spring framework 5 comes with a new module called spring-webflux to support building reactive web applications.
Spring WebFlux by default uses Project Reactor, which is an implementation of reactive streams for reactive support. But you can use other reactive streams implementations, like RxJava, as well. The spring-webflux module provides support for creating reactive server applications as well as reactive client applications using REST, HTML browsers, and WebSocket style communications.
Spring WebFlux can run on servlet containers with support for Servlet 3. As of now, relational database vendors havent provided non-blocking driver implementations. Now youll develop a reactive web application with Spring WebFlux using the annotation based programming model. Use the embedded MongoDB server by adding the following dependency so that you dont need to install the MongoDB server.
Id; import org. Flux; import reactor. One key point to remember is that, unless someone subscribes to the reactive stream pipeline, nothing happens. For example, the following method doesnt insert the user document in MongoDB. This just defined the stream pipeline, but nobody subscribed to it, so nothing happens. The following code will insert the user document because it is explicitly calling subscribe on the pipeline.
The UserController. Hence, it works as expected. WebFlux Using a Functional Programming Model Spring framework 5 introduced a new functional style programming model built on top of the reactive foundation in addition to the annotation based programming model.
Instead of using annotations to define request handling methods, you can implement HandlerFunctions as Java 8 lambdas and map the request URL patterns to HandlerFunctions using RouterFunctions. You can write the same code block using Java 8 lambdas and static imports in a much more concise way, as follows:.
0コメント