Spring and Spring Boot

Preview:

Citation preview

Spring and Spring Boot

CAS Java Microservice Development

Simon Martinelli, simon.martinelli@bfh.ch, v2020.02

Overview

2

From Application to Platform

Application

InfrastructureCode

Application

Library

Framework

Application

Java Platform

Web Container

Components

EJB Container

Components

Services

3

Platform

4

OS / Distributed System

Communication Infrastructure

Application-Oriented Middleware / Java Platform

Services

Container

Components Components Components Components Components

Container, Services and Components

5

Platform

Container Service

Components

providescontains

runs in uses

-

Principles and Patterns1. Injection and Factory

2. Context

3. Proxy

4. Interceptors

6

Martin Fowler, 2004http://martinfowler.com/articles/injection.html 7

▶ The question is, what aspect of control are [they] inverting?

▶ Martin Fowler asked this question about Inversion of Control (IoC) in 2004 on his website

▶ Fowler made the proposal to rename the Principle “Dependency Injection”so that it is self-explanatory

Background

8

A Naive Approach

9

▶ Problems

▶ Strong coupling

▶ Hard to extend

Traditional Method

10

private MovieFinder finder;

public MovieLister() {finder = new ColonDelimitedMovieFinder("movies1.txt");

}

Factory Patterns

Abstract Factory Factory Method

11

▶ Problems

▶ Unnecessary code

▶ Problem moved to the factory

▶ How is the factory configured?

Solution: Factory Method

12

public class MoveFinderFactory() {

public static MovieFinder createMovieFinder(String f) {return new ColonDelimitedMovieFinder(f);

}}

Solution: Service Locator

13

▶ Don't call us - we call you! (Hollywood Principle) = Inversion of Control

▶ Relationships are set from the outside

▶ Constructor

▶ Field

▶ Setter

▶ Frameworks

▶ Java EE

▶ Spring

▶ Google Guice

▶ and many more..

Solution: Dependency Injection

14

Assembler

15

1. Annotations

▶ Starting from Java 5

▶ Complier checked

▶ Business code “contamination"

2. XML

▶ No recompile for configuration changes

▶ Prone to errors (mostly IDE checked)

Metadata

16

▶ The life cycle and the interactions of stateful components are linked to well-defined but extensible contexts

Context and Scopes

17

Application/Singleton

Session

Request

▶ Request - A user interaction with a web application with an HTTP request or retrieval of a stateless session bean

▶ Session - A user interaction with a web application through multiple HTTP requests or all requests for a stateful session bean

▶ Application/Singleton - Shared state of all user interactions of a web application or all requests for a singleton session bean

Scopes

18

▶ The scope gives an object a well-defined lifecycle context

▶ An object is automatically created during first use

▶ The object is automatically destroyed when the context ends

Scope Management

19

Proxy

20

▶ A proxy in its most general form is a class that acts as an interface to another “subject"

▶ This subject may, for example, be a network connection, a large object in the memory, a file or another resource

▶ As the representative of this subject the proxy can control the generation of the subject as well as access to it

▶ Proxies can also be used to prevent further operations on actual access to the object. The object thus remains independent of these operations

Proxy

21

▶ Virtual Proxy Imagine a situation where there is a multiple database call to extract a very large image. Since this is an expensive operation, we could potentially use the proxy pattern which would create multiple proxies and highlight the large, memory-consuming object for further processing. The real object is only created when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object, hence saving memory.

▶ Remote ProxyA remote proxy can be thought about as a stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing an interface for remote resources such as web service or REST resources.

Proxy Scenarios

22

▶ Protective ProxyThe protective proxy acts as an authorization layer to verify whether the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and content which are valid will be allowed and the remaining ones will be blocked.

▶ Smart Proxy A smart proxy provides an additional layer of security by interposing specific actions when the object is accessed. An example could be to check if the real object is locked before it is accessed to ensure that no other object can change it.

Proxy Scenarios

23

Interceptor

24

Interceptor

Component A Component B

▶ The Interceptor pattern provides the possibility to transparently incorporate functionality into a framework

▶ This is important especially if different applications need to access a framework and need special services, which are not provided directly through the framework

▶ By using the interceptor pattern this functionality does not have to be integrated into the framework

▶ This would help to keep its structure simple without having to omit the extended functionality

Interceptor

25

▶ Aspect-Oriented Programming (AOP) is a programming paradigm using generic functionalities across multiple classes Cross-Cutting Concerns

▶ Logical aspects of an application program are thereby separated from actual business logic

▶ Typical examples of applications include transaction management, auditability and logging

▶ The concept of AOP was developed by Gregor Kiczales and his team at the company Xerox PARC

▶ In 2001, the first AOP language AspectJ was also presented there

AOP - Aspect Oriented Programming

26

Advice

27

28

J2EE Java EE Jakarta EE

https://jakarta.ee/

29

History

30

Open Source

September 2019

Java EE Specifications

31

Layers

32

Container

33

THE APPLICATION SERVER

< 1999 > 1999

34

MAINFRAME APPLICATION SERVER

Shared Platform

35

OS / Distributed System

Communication infrastructure

Java EE Application Server

Services

Container

EAR1 EAR2 WAR1 WAR2 WAR3

Java Virtual Machine

Dedicated Platform

36

OS / Distributed System

Communication infrastructure

Java EE Application Server

Services

Container

WAR

Java Virtual Machine

Executable JAR

Self Hosted

37

OS / Distributed System

Communication infrastructure

Middleware

Services

Container

Java Virtual Machine

Spring Framework

38

▶ Spring makes it easy to create Java enterprise applications

▶ Spring supports a wide range of application scenarios

▶ applications that run on an application server

▶ applications that run as single JAR with the server embedded (possibly in the cloud)

▶ standalone applications (such as batch workloads)

Overview

39

Spring Framework History

40

2002 2004

▶ https://spring.io

▶ Spring was created by Interface21

▶ Later renamed to Spring Source

▶ And now developed by Pivotal (VMWare)

▶ The Open Source-Project started in February 2003

▶ Apache 2.0 License

▶ https://github.com/spring-projects/spring-framework

The Project

41

42

Java EE vs Spring

43

Not really…

▶ POJO-based development

▶ Generic component model for application development

▶ Flexible easy to use alternative to EJBs without being bound to J2EE

▶ Application components are decoupled

▶ Instantiation, initialization, configuration and binding done by Inversion ofControl / Dependency Injection framework

▶ Components without dependencies to Spring (non-invasive)

▶ Runs many runtime environments from standalone to full-scale Java EE application server

▶ Generic Middleware-Services

▶ Provided through AOP

▶ Uses services from Java EE-Application-Servers if possible

Goals

44

▶ The Spring framework is divided into modules

▶ The core modules include a configuration model and a dependency injection mechanism

Spring Framework

45

▶ Distributed/versioned configuration

▶ Service registration and discovery

▶ Routing

▶ Service-to-service calls

▶ Load balancing

▶ Circuit Breakers

▶ Global locks

▶ Leadership election and cluster state

▶ Distributed messaging

Spring Cloud

46

-

Beans

47

▶ The core of the Spring framework is the Spring container (a.k.a. IoC container)

▶ The Spring container is the runtime environment of beans (components) and responsible for

▶ the lifecycle of beans

▶ the configuration of beans

▶ the injection of dependencies

Spring Container

48

▶ Beans define their dependencies through fields, setter methods, or constructor arguments

▶ But the beans do not control the instantiation or location of their dependencies

▶ The IoC container injects the dependencies when it creates the beans

Inversion of Control (IOC)

49

▶ Spring beans are represented as BeanDefinition objects which contain

▶ a unique identifier

▶ the fully-qualified class name

▶ behavioral elements (scope, lifecycle callbacks)

▶ references to other beans (collaborators or dependencies)

▶ other settings (e.g. the size limit of a connection pool)

▶ The Spring container manages beans using configuration metadata

Spring Beans

50

▶ Spring provides different bean annotations▶ @Component is a generic annotation for any Spring-managed component

▶ @Repository, @Service, and @Controller are specializations for the persistence, service, and presentation layer which can carry additional semantics

▶ The annotations have an optional value attribute which represents the component's name

Bean Annotations

51

▶ The scope of a bean determines its lifetime

▶ Spring supports the following scopes (the last four only for web applications)

▶ singleton single instance for each container (default)

▶ prototype any number of object instances

▶ request lifecycle of a single HTTP request

▶ session lifecycle of an HTTP Session

▶ application lifecycle of a servlet context

▶ websocket lifecycle of a web socket

▶ The singleton scope should be used for stateless, the prototype scope for stateful beans

Bean Scopes

52

▶ A bean can implement callback methods to interact with the container's lifecycle management▶ PostConstruct lets a bean perform initialization work after the container has

injected the dependencies▶ PreDestroy lets a bean perform clean-up work before the container is

destroyed

Lifecycle Callbacks

53

-

Dependency Injection (DI)

54

▶ With dependency injection, code becomes cleaner, decoupling is more effective, and classes are easier to test

▶ Beans can define their dependencies through fields, setter methods, or constructor arguments

▶ Dependency injection is based on the type of the component to be injected

Dependency Injection (DI)

55

▶ With field injection, the container sets the value of a field on the bean using reflection

▶ Field injection is discouraged because dependencies are hidden and the bean cannot be instantiated without reflection

Field Injection

56

▶ With setter injection, the container calls setter methods on the bean after instantiating it

▶ Setter injection should only be used for optional dependencies that can be assigned reasonable default values

Setter Injection

57

▶ With constructor injection, the container invokes a constructor with arguments representing the dependencies

▶ Constructor injection allows beans to be implemented as immutable objects and ensures that required dependencies are not null

▶ If the bean has only one constructor, the @Autowired annotation can be omitted

Constructor Injection

58

Microservice Frameworks

59

Frameworks, Frameworks, Frameworks

60Source https://www.java-forum-stuttgart.de/_data/2019_G5_Schwoerer.pdf

-

Microprofile.io

https://microprofile.io/

61

Enterprise Java for a Microservices Architecture

62

GraalVM

63

GraalVM

64

GraalVM

65

-

Spring Boot

66

67

▶ Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run"

▶ We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss

▶ Most Spring Boot applications need very little Spring configuration

What’s Spring Boot?

68

▶ Create stand-alone Spring applications

▶ Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

▶ Provide opinionated 'starter' POMs to simplify your Maven configuration

▶ Automatically configure Spring whenever possible

▶ Provide production-ready features such as metrics, health checks and externalized configuration

▶ Absolutely no code generation and no requirement for XML configuration

Spring Boot Features

69

▶ Starters are a set of convenient dependency descriptors that you can include in your application.

▶ You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors

▶ For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project

▶ The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies

Spring Boot Starters

70

▶ Spring Boot Website

▶ https://spring.io/projects/spring-boot

▶ Reference Documentation

▶ Spring Initializer

▶ https://start.spring.io/

On your mark, ready, GO!

71

▶ The SpringApplication class with its static run method provides a convenient way to bootstrap a Spring application

▶ The meta-annotation @SpringBootApplication consists of the following annotations:▶ @Configuration allows to register beans or to import configuration classes

▶ @ComponentScan enables scanning of components on the application's package

▶ @EnableAutoConfiguration enables the auto-configuration mechanism

Application

72

▶ If code needs to be run once, a bean can implement the CommandLineRunnerinterface

▶ The interface defines a run method, which is called before the run method of SpringApplication completes

▶ The command line arguments are passed as parameters

CommandLineRunner

73

▶ For the development of Spring applications, a build tool such as Maven or Gradle is recommended

▶ Each release of Spring Boot provides a list of supported dependencies

▶ https://spring.io/projects/spring-boot

▶ https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

▶ A convenient way to create a Spring project is to use the Spring Initializr

▶ https://start.spring.io/

Development

74

▶ Maven projects can inherit from the spring-boot-starter-parent project whichprovides dependency management and some sensible configurations<parent>

<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.0.RELEASE</version>

</parent>

▶ Starters are dependency descriptors for a particular types of applications<dependency>

<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId>

</dependency>

▶ The Spring Boot Maven plugin is used to run and to package an application<plugin>

<groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

Maven Projects

75

▶ A Spring Boot Maven application can be run in the exploded form using the run goal of the Maven plugin> mvn spring-boot:run

▶ The plugin also allows a Spring Boot application to be packaged as a single JAR that can be run using the java command> java -jar target/myapplication-1.0.jar

▶ If the application starts successfully, the Spring Boot banner is displayed

▶ If an application fails to start, failure analyzers try to provide a dedicated error message

▶ The full evaluation conditions report can be displayed by enabling the debug property

Running an Application

76

▶ The following code stucture is recommended

▶ The main application class is located in a root package

▶ For each application domain, a different sub-package is provided

Code Structure

77

Recommended