34,79 €
Kotlin is being used widely by developers because of its light weight, built-in null safety, and functional and reactive programming aspects. Kotlin shares the same pragmatic, innovative and opinionated mindset as Spring, so they work well together. Spring when combined with Kotlin helps you to reach a new level of productivity. This combination has helped developers to create Functional Applications using both the tools together. This book will teach you how to take advantage of these developments and build robust, scalable and reactive applications with ease.
In this book, you will begin with an introduction to Spring and its setup with Kotlin. You will then dive into assessing the design considerations of your application. Then you will learn to use Spring (with Spring Boot) along with Kotlin to build a robust backend in a microservice architecture with a REST based collaboration, and leverage Project Reactor in your application. You’ll then learn how to integrate Spring Data and Spring Cloud to manage configurations for database interaction and cloud deployment. You’ll also learn to use Spring Security to beef up security of your application before testing it with the JUnit framework and then deploying it on a cloud platform like AWS.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 188
Veröffentlichungsjahr: 2018
Miloš Vasić
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Aaron LazarAcquisition Editor: Sandeep MishraContent Development Editor: Zeeyan PinheiroTechnical Editor: Ketan KambleCopy Editor:Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonteiroProduction Coordinator: Shantanu Zagade
First published: May 2018
Production reference: 1170518
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-480-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Miloš Vasić is a software engineer, author, and open source enthusiast. Miloš holds a bachelor's degree in the programming of computer graphics and a master's degree in the field of Android programming; he obtained both degrees at Singidunum University. He published his first book, Fundamental Kotlin, in October 2016 and thus achieved his dream of becoming an author. When he is not writing a new book, Miloš can be found working on his open source projects.
Mario Arias is a software engineer and Spring certified instructor with more than 12 years of experience in software development and design, databases, training material design, and training delivery. He currently works as a software engineer in Manchester, UK, for Cake Solutions Ltd., a BAMTECH media company.
Mario is a well-known member of the Kotlin community and is part of the Arrow team, the group that developed and maintains the Arrow functional library. In his free time, he rides his bicycle and trains in Brazilian Jiu-Jitsu.
Nenad Đorđević has 22 years of experience in software development, engineering, and project and team management for software solutions developed in Java and JavaScript. He has been a part of international projects at U.S.Steel Kosice and U.S.Steel North America.
Nenad's expertise and career goals are focused on designing full-stack solutions using Java, Spring, and JavaScript modern frameworks.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Building Applications with Spring 5 and Kotlin
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Starting Up
What is your mission?
Separating code into independent entities
Describing entities
Planning your development
Preparing the working environment
Installing Git
Microsoft Windows
macOS
Linux
Debian and Ubuntu
Fedora
Building Git from the source code
Debian and Ubuntu
Fedora
Installing JDK
Microsoft Windows
Linux
macOS
Installing the IDE
Microsoft Windows
Linux
macOS
Starting IntelliJ for the first time
Installing Spring 5
Maven installation
Gradle installation
Installing Postman
Microsoft Windows installation
Linux installation
macOS installation
Setting up a Git repository
Summary
Starting with Spring
What is Spring?
What features does it offer?
Dependency injection
Inversion of Control (IoC)
Aspect Oriented Programming (AOP)
Container
MVC framework
Model
View
Controller
Transaction management
Misc
How well is Kotlin supported?
Creating Spring project
What is Spring Initializr?
Generating the project
Creating Spring project with IntelliJ
Summary
Building Your First Spring RESTful Service with Kotlin
Defining dependencies for our project
Our first controller
What else is available?
Adding a data class
Drafting other API calls
Running the application
Accessing Actuator endpoints
Adding an @Service component
Summary
Working with Spring Data JPA and MySQL
Introducing Spring Data JPA
What does Spring Data provide?
Which Spring Data modules do we need?
About Spring Data JPA
Installing MySQL
Installing MySQL Community Server on macOS
Installing MySQL Community Server on Windows
Installing MySQL Community Server on Linux
Using a software package manager
Using TAR
Creating a schema
Extending dependencies
CRUD operations
Insert
Update
Select
Delete
More regarding updates
Introducing DTOs
Creating database queries
Named queries
Summary
Securing Applications with Spring Security
Introducing Spring Security
Defining user roles
Defining classes for each role
Defining DTOs for the user
Securing your REST API with basic authentication
What else can Spring Security do?
Summary
Spring Cloud
Microservice architecture versus SOA
Understanding microservice architectures
Microservices with Spring Cloud
Spring Cloud in practice
Configuration server
Discovery
Gateway
Updating the API application
Securing Spring Cloud services
Summary
Using Project Reactor
Why use Project Reactor?
What is Project Reactor?
Using Project Reactor
Summary
Development Practices
Challenging development practices
Reviewing dependency injection
Making your classes too open
Mutability
Multithreading
Not validating data
Tests coverage
XML configurations
Good ways to develop your code
Don't inject too much
Use a closed-visibility approach
Solving the multithreading issue
Spring data validation
Summary
Testing
Why is testing a crucial part of development?
So, what is testing?
Common test practices and approaches
Preparing our project
Writing our first test with Kotlin
Running the test in InteliJ IDEA
Testing Spring REST applications
Running test suites
Summary
Project Deployment
What will be deployed?
Deployment options
Deploying the Tomcat application server
Deploying to the Java EE application server
Deploying to the Cloud (AWS)
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Spring is the most popular framework for web development and, every year, more and more developers are getting involved in Spring development. Spring Framework makes it possible to develop applications for the web, especially RESTful and other types of services. So far, all development has been undertaken in Java. Recently, Kotlin has become very popular! Due to this, and the huge growth of the Kotlin community, we decided to introduce you to Spring development by using Kotlin as the primary development programming language.With Kotlin, you can do everything you could do with Java, but with more joy and fun! We will show you how to play with Spring and Kotlin and how to create amazing things! Take your seat and get ready for an amazing journey!
This book is designed for people who would like to learn the Spring Framework, and who have a basic knowledge of Kotlin, but not of Spring. It's intended as a guide for newbie Spring programmers. In this book, all examples are given in pure Kotlin.
Chapter 1, Starting Up, starts preparing the working environment by setting up Git repositories. After we do that, we will use Gradle as a tool to shape our project and its modules.
Chapter 2, Starting with Spring, shows how to set up our development environment. We will be ready to create our first Spring code written in Kotlin.
Chapter 3, Building Your First Spring RESTful Service with Kotlin, defines the Spring project and lists examples along with tips on how to write nice and clean REST services with Spring using Kotlin.
Chapter 4, Working with Spring Data JPA and MySQL, describes Spring Data. We will see how to create a data repository with CRUD operations on some entity. Finally, we will learn how to make queries on the MySQL database.
Chapter 5, Securing Applications with Spring Security, presents Spring Security projects and shows some examples of how to utilize Basic Authentication and/or OAuth2.
Chapter 6, Spring Cloud, explains the difference between the microservice architecture and SOA. At the end, we will see how to use the Spring Cloud project to implement the microservice architecture in its own application.
Chapter 7, Using Project Reactor, discusses the advantages of reactive programming. We will present Project Reactor and teach the reader how to use its power in its applications.
Chapter 8, Development Practices, talks about some good and some not-so-good practices.
Chapter 9, Testing, explains the importance of well-tested code. We will see how to write JUnit tests with Kotlin and how to write tests for Spring-based applications.
Chapter 10, Project Deployment, finally, presents the different options for deploying Spring applications. We will also see how to deploy REST service to the Tomcat application server or to AWS. If you are a fan of AWS, this is a great topic for you!
To get the most out of this book, read it slowly and carefully and do each of the examples we do. Try to understand the point behind the example given and how you would use it as a base to build something bigger. Also, as always, code as much as you can!
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Applications-with-Spring-5-and-Kotlin. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/BuildingApplicationswithSpring5andKotlin_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Double-click theideaIC.dmgorideaIU.dmgfile you have downloaded to mount the macOS disk image."
A block of code is set as follows:
repositories { maven { url 'https://repo.spring.io/libs-milestone' } } dependencies { compile 'org.springframework:spring-context:5.0.0.RC4' }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
repositories { maven { url 'https://repo.spring.io/libs-milestone' } } dependencies {
compile 'org.springframework:spring-context:5.0.0.RC4'
}
Any command-line input or output is written as follows:
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "You can choose between the default theme and the Darcula theme."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Welcome! You are starting a long trip into the unknown: the unknown kingdom of Spring Framework. Luckily, you have the right guide and great companions! You have us! In this book, you will discover what Spring Framework is and how powerful it can be in modern web application development. We will teach you all about workflow with the framework and guide you through a real-world application example. Get ready to learn!
This chapter will cover the following points:
Defining your mission
Separating code into independent entities
Planning your environment
Preparing the working environment
Setting up a Git repository
Your mission, as we mentioned, will be making a real-world application. What can be a better learning path than building real things from scratch through to production deployment? Our real-world application example will have a real theme!
We will create a REST application that will represent the application programming interface (API) for other applications. The theme for our application will be simple: management for user Notes and TODOs.
Imagine that there is a real-world mobile application that manages all these Notes and TODOs. That application will need a REST API so that all the data is synchronized to the backend. The story is simple. The user creates a Note or TODO. The user's mobile application then, at some point, does the synchronization. After some time, the user updates the content in it. Again, data is synchronized with the remote backend instance. Then, after a year, the user buys a new device that has a plain mobile application running. Luckily, the mobile application will synchronize with the remote backend instance again and get all the Notes and TODOs the user created.
So, what will this REST API do?
It will expose to the end user API calls for all Create, Read, Update, and Delete (CRUD) operations. The data we create or modify will be stored in the persistence layer. In our case, that will be MySQL database. Using Spring Security, we will create user roles so certain user profiles can do various things, such as creating the other users or modifying the main application content. To make things more interesting, we will create microservices responsible for various tasks.
Before we deploy, we will first test our code with the proper tests. We will also write unit tests. All tests will cover some of the core functionality so that our application is sufficiently stable to be deployed. We will deploy to Apache Tomcat and to Amazon AWS Elastic Beanstalk.
Before we start with the implementation, we will separate our code into independent entities. Each entity will cover a single responsibility and therefore will be implemented when we cover a certain Spring functionality.
We will start with the main classes that will represent the data we will actually handle: Notes and TODOs. Then we will describe user-related stuff: the users themselves and the roles we plan to assign to them. Later, when we actually implement most of them, we will introduce some new entities to cover additional responsibilities. This will be explained in Chapter 3, Building Your First Spring RESTful Service with Kotlin.
The main entities that we will use and that will hold the data are Notes and TODOs. We can consider each of them as an entry that will be stored and that has common attributes:
ID
:
Universally Unique IDentifier
(
UUID
) String
Title
: String
Message
: String
Location
: String value that represents serialized Location class into JSON.
Here are all the entities that we use:
Note
: The
Note
entity will represent Notes in the system with all common attributes.
TODO
:The
TODO
entity will represent TODOs in the system with all common attributes and timestamps for a scheduled time.
User
: The
User
entity will be completely independent of the main data entities. The user will represent the user and all the attributes that the user of the system can have, including assigned roles. The user will have the following attributes:
ID
: UUID
String
: String
Password
: String
First name
: String
Last name
: String
Roles
: String
Enabled
: Boolean representing whether the user has activated the account or whether it has been activated by the user from a higher user hierarchy
Created on
: Long representing UTC timestamp when the user was created
Updated on
: Long representing UTC timestamp when the user was updated
In later stages, we can introduce additional attributes if there is a need. For now, we will stick to the most important ones we just described.
For every project you do, for big and complex projects, and for small ones too, planning is crucial!We will plan our development according to the chapter structure of this book. So, some stuff will be done first and some later. As you have probably realized, user-related functionalities will be provided when we touch on Spring Security. Until then, we will be focused on the main data entities and their relationship with Spring Framework and API clients as well.
Before you get into the deep implementation, it would be wise to plan your work first. As we already did, you should identify all your entities and the relations between them. You must be aware of potential hard connections between them. The best scenario is that each entity is completely independent and not aware of others. In our case, the user entity does not have any awareness of our main data entities, Notes, and TODOs, and vice versa.
Then, if we put all this on paper, we can consider what environments we will have. A common practice is that we have development, staging, and production environments. For bigger projects, sometimes a preproduction environment is also used. In our case, we will have a local development environment, too. The local development environment will be the one we will use for all these exercises. We will use our local working machines running an instance of MySQL and our Spring Framework application.
You must plan how will you deploy the application. For example, an application can run on Apache Tomcat or Amazon AWS. These are not the only options available. Depending on your needs, you will choose a proper deployment platform and deployment scenario. We will discuss this in more detail in Chapter 10, Project Deployment.
