Apress pro spring boot

373 883 0
Apress pro spring boot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

T HE E X P ER T ’S VOIC E ® IN SP R ING Pro Spring Boot A no-nonsense guide containing case studies and best practices for Spring Boot — Felipe Gutierrez Pro Spring Boot Felipe Gutierrez Pro Spring Boot Felipe Gutierrez Albuquerque New Mexico, USA ISBN-13 (pbk): 978-1-4842-1432-9 DOI 10.1007/978-1-4842-1431-2 ISBN-13 (electronic): 978-1-4842-1431-2 Library of Congress Control Number: 2016941344 Copyright © 2016 by Felipe Gutierrez This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Manuel Jordan Elera Editorial Board: Steve Anglin, Pramila Balan, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Mark Powers Copy Editor: Kezia Endsley Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com/9781484214329 For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter Printed on acid-free paper To my wife, Norma Castaneda Contents at a Glance About the Author xiii About the Technical Reviewer xv Acknowledgments xvii ■Chapter 1: Introduction to Spring Boot ■Chapter 2: Your First Spring Boot Application ■Chapter 3: Spring Boot Auto-Configuration, Features, and More 43 ■Chapter 4: Spring Boot CLI 73 ■Chapter 5: Spring with Spring Boot 89 ■Chapter 6: Testing with Spring Boot 107 ■Chapter 7: Data Access with Spring Boot 121 ■Chapter 8: Web Development with Spring Boot 149 ■Chapter 9: Security with Spring Boot 177 ■Chapter 10: Messaging with Spring Boot 211 ■Chapter 11: Spring Boot Actuator 245 ■Chapter 12: Deploying Spring Boot 283 ■Chapter 13: Spring Boot in the Cloud 307 ■Chapter 14: Extending Spring Boot Apps 335 ■Appendix: Spring Boot 1.4.x 357 Index 361 v Contents About the Author xiii About the Technical Reviewer xv Acknowledgments xvii ■Chapter 1: Introduction to Spring Boot Spring Boot Spring Applications Spring Boot to the Rescue Why Spring Boot? Spring Boot Features Summary ■Chapter 2: Your First Spring Boot Application Installing Spring Boot CLI UNIX OSs: Linux, OS X, and Solaris Windows OS 11 Spring Boot with Maven and Gradle 13 Using Maven 13 Using Gradle 14 Spring Boot Using External Tools 16 Spring Boot Using the Spring Initializr 16 Using the Spring Initializr with UNIX cURL 18 Spring Boot Using Spring Tool Suite (STS) 19 vii ■ CONTENTS Your First Spring Boot Application 24 Spring Boot Journal 24 How Spring Boot Works 39 Summary 41 ■Chapter 3: Spring Boot Auto-Configuration, Features, and More 43 Auto-Configuration 43 Disabling a Specific Auto-Configuration 45 @EnableAutoConfiguration and @Enable Annotations 47 Spring Boot Features 49 SpringApplication Class 51 SpringApplicationBuilder 56 Application Arguments 58 ApplicationRunner and CommandLineRunner 60 Application Configuration 62 Configuration Properties Examples 63 Custom Properties Prefix 69 Summary 72 ■Chapter 4: Spring Boot CLI 73 Spring Boot CLI 73 The run Command 74 The test Command 76 The grab Command 78 The jar Command 79 The war Command 80 The install Command 81 The uninstall Command 81 The init Command 82 The shell Command 85 The help Command 86 Summary 87 viii ■ CONTENTS ■Chapter 5: Spring with Spring Boot 89 Spring Web Applications 89 J2EE Web Applications 89 Spring MVC Applications 93 Spring Boot Web Applications 98 Using Spring with Spring Boot 101 XML with Spring Boot 101 Groovy Beans in Spring Boot 102 Standalone Spring Apps vs Spring Boot Apps 103 Using Spring Technologies in Spring Boot 104 Summary 105 ■Chapter 6: Testing with Spring Boot 107 Testing Spring Boot 107 Web Testing 109 Summary 120 ■Chapter 7: Data Access with Spring Boot 121 SQL Databases 121 Data Access Using the JDBC Template with Spring Boot 122 Data Access Using JPA with Spring Boot 131 NoSQL Databases 140 Summary 147 ■Chapter 8: Web Development with Spring Boot 149 Spring MVC 149 Spring Boot Web Applications 150 Playing with the HAL Browser 171 Summary 175 ix CHAPTER 14 ■ EXTENDING SPRING BOOT APPS import com.apress.spring.config.JournalProperties; @SpringBootApplication @RestController public class SpringBootCalendarApplication { public static void main(String[] args) { SpringApplication.run(SpringBootCalendarApplication.class, args); } private static final String VIEW_INDEX = "index"; @Autowired JournalProperties journal; @RequestMapping(value="/", method = RequestMethod.GET) public ModelAndView index(ModelAndView modelAndView){ modelAndView.setViewName(VIEW_INDEX); modelAndView.addObject("journal", journal); return modelAndView; } } Listing 14-10 shows the main application You basically already know all the annotations in this class, but it’s good to mention that the JournalProperties instance is available and you will be using it to access its values in the index page Next, let’s see the application.properties Remember that you can now override those properties as well Its content is shown in Listing 14-11 Listing 14-11 src/main/resources/application.properties journal.api-path=/myapi journal.context-path=/myjournal Listing 14-11 shows the application.properties that you will use in this second run to see if the defaults can be overridden For now it doesn’t have the journal.banner property (with the value /META-INF/banner/journal.txt); you can play around with it later Now let’s see the index.html page (you need to create the templates folder) See Listing 14-12 Listing 14-12 src/main/resource/templates/index.html Spring Boot Calendar 350 CHAPTER 14 ■ EXTENDING SPRING BOOT APPS Spring Boot Calendar Spring Boot Calendar

This is a small Calendar application, showing the power of Spring Boot auto-configuration features This Calendar application also provides you a full access to the Journal Web UI

Journal

Spring Boot Calendar, powered by Spring Boot.

Listing 14-12 shows index.html and the important part is the usage of the journal object that is sent from the controller (the JournalProperties instance) Regardless of which path you add for the API or the journal you will be always have the right endpoint Before you run it, you need to have the cover.css file that is located in the static/css folder (you need to create the static folder as well) The bootstrap.min.css is being picked up from the journal module, so you don’t need it here You can get this code from the Apress site (Or you can get it from the GitHub at https://github.com/felipeg48/pro-spring-boot) 351 CHAPTER 14 ■ EXTENDING SPRING BOOT APPS Now you are ready to run it: $ /mvnw spring-boot:run If you go directly to the root at http://localhost:8080/, you will see something like Figure 14-3 Figure 14-3 The calendar application home page Figure 14-3 shows the calendar app You can test the links declared in the index.html file and see if the endpoints actually work because they should have taken the values of the properties specified in the application.properties file So, click the Journal button and you should get sent to the /myjournal endpoint If you click at the top of the page in the navigation bar, the API menu option, you should be sent to the /myapi endpoint and be able to read all about the RESTful services Congratulations! You have just created your custom Spring Boot starter! 352 CHAPTER 14 ■ EXTENDING SPRING BOOT APPS Custom Health Indicator Another way to extend your Spring Boot application is to add your own health indicator when you are using the spring-boot-actuator module It would be nice to have a way to monitor specific requirements; for example, imagine that you want your calendar be able to monitor how many entries you have in your journal In other words, you can have customers who want to use your calendar application and you want to limit the entries per journal You’ll build a quota health monitor for that purpose You will continue using the Calendar project The spring-boot-starter-actuator is missing in your pom.xml in order to activate the health endpoints So add this to your pom.xml: org.springframework.boot spring-boot-starter-actuator Next, let’s create two classes that will define the quota monitor The first class is a standard exception handler See Listing 14-13 Listing 14-13 src/main/java/com/apress/spring/health/QuotaException.java package com.apress.spring.heatlh; public class QuotaException extends Exception { private static final long serialVersionUID = -1L; public QuotaException(String ex){ super(ex); } } Listing 14-13 shows a simple class that extends from exception and overrides the constructor with a String parameter; this is nothing new that you don’t already know Next is the most important part to create the monitor See Listing 14-14 Listing 14-14 src/main/java/com/apress/spring/health/QuotaHealthIndicator.java package com.apress.spring.heatlh; import import import import org.springframework.beans.factory.annotation.Autowired; org.springframework.boot.actuate.health.Health; org.springframework.boot.actuate.health.HealthIndicator; org.springframework.stereotype.Component; import com.apress.spring.repository.JournalRepository; 353 CHAPTER 14 ■ EXTENDING SPRING BOOT APPS @Component public class QuotaHealthIndicator implements HealthIndicator{ private static final Long QUOTA_MAX_SIZE = 10L; @Autowired JournalRepository repo; @Override public Health health() { long size = repo.count(); if(size

Ngày đăng: 12/05/2017, 14:32

Từ khóa liên quan

Mục lục

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewer

  • Acknowledgments

  • Chapter 1: Introduction to Spring Boot

    • Spring Boot

      • Spring Applications

      • Spring Boot to the Rescue

      • Why Spring Boot?

      • Spring Boot Features

      • Summary

      • Chapter 2: Your First Spring Boot Application

        • Installing Spring Boot CLI

          • UNIX OSs: Linux, OS X, and Solaris

          • Windows OS

          • Spring Boot with Maven and Gradle

            • Using Maven

            • Using Gradle

            • Spring Boot Using External Tools

              • Spring Boot Using the Spring Initializr

              • Using the Spring Initializr with UNIX cURL

              • Spring Boot Using Spring Tool Suite (STS)

              • Your First Spring Boot Application

                • Spring Boot Journal

                • How Spring Boot Works

                • Summary

Tài liệu cùng người dùng

Tài liệu liên quan