spring and spring boot

77
Spring and Spring Boot CAS Java Microservice Development Simon Martinelli, [email protected], v2020.02

Upload: others

Post on 24-Feb-2022

63 views

Category:

Documents


9 download

TRANSCRIPT

Page 1: Spring and Spring Boot

Spring and Spring Boot

CAS Java Microservice Development

Simon Martinelli, [email protected], v2020.02

Page 2: Spring and Spring Boot

Overview

2

Page 3: Spring and Spring Boot

From Application to Platform

Application

InfrastructureCode

Application

Library

Framework

Application

Java Platform

Web Container

Components

EJB Container

Components

Services

3

Page 4: Spring and Spring Boot

Platform

4

OS / Distributed System

Communication Infrastructure

Application-Oriented Middleware / Java Platform

Services

Container

Components Components Components Components Components

Page 5: Spring and Spring Boot

Container, Services and Components

5

Platform

Container Service

Components

providescontains

runs in uses

Page 6: Spring and Spring Boot

-

Principles and Patterns1. Injection and Factory

2. Context

3. Proxy

4. Interceptors

6

Page 7: Spring and Spring Boot

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

Page 8: Spring and Spring Boot

▶ 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

Page 9: Spring and Spring Boot

A Naive Approach

9

Page 10: Spring and Spring Boot

▶ Problems

▶ Strong coupling

▶ Hard to extend

Traditional Method

10

private MovieFinder finder;

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

}

Page 11: Spring and Spring Boot

Factory Patterns

Abstract Factory Factory Method

11

Page 12: Spring and Spring Boot

▶ 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);

}}

Page 13: Spring and Spring Boot

Solution: Service Locator

13

Page 14: Spring and Spring Boot

▶ 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

Page 15: Spring and Spring Boot

Assembler

15

Page 16: Spring and Spring Boot

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

Page 17: Spring and Spring Boot

▶ 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

Page 18: Spring and Spring Boot

▶ 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

Page 19: Spring and Spring Boot

▶ 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

Page 20: Spring and Spring Boot

Proxy

20

Page 21: Spring and Spring Boot

▶ 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

Page 22: Spring and Spring Boot

▶ 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

Page 23: Spring and Spring Boot

▶ 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

Page 24: Spring and Spring Boot

Interceptor

24

Interceptor

Component A Component B

Page 25: Spring and Spring Boot

▶ 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

Page 26: Spring and Spring Boot

▶ 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

Page 27: Spring and Spring Boot

Advice

27

Page 28: Spring and Spring Boot

28

Page 29: Spring and Spring Boot

J2EE Java EE Jakarta EE

https://jakarta.ee/

29

Page 30: Spring and Spring Boot

History

30

Open Source

September 2019

Page 31: Spring and Spring Boot

Java EE Specifications

31

Page 32: Spring and Spring Boot

Layers

32

Page 33: Spring and Spring Boot

Container

33

Page 34: Spring and Spring Boot

THE APPLICATION SERVER

< 1999 > 1999

34

MAINFRAME APPLICATION SERVER

Page 35: Spring and Spring Boot

Shared Platform

35

OS / Distributed System

Communication infrastructure

Java EE Application Server

Services

Container

EAR1 EAR2 WAR1 WAR2 WAR3

Java Virtual Machine

Page 36: Spring and Spring Boot

Dedicated Platform

36

OS / Distributed System

Communication infrastructure

Java EE Application Server

Services

Container

WAR

Java Virtual Machine

Page 37: Spring and Spring Boot

Executable JAR

Self Hosted

37

OS / Distributed System

Communication infrastructure

Middleware

Services

Container

Java Virtual Machine

Page 38: Spring and Spring Boot

Spring Framework

38

Page 39: Spring and Spring Boot

▶ 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

Page 40: Spring and Spring Boot

Spring Framework History

40

2002 2004

Page 41: Spring and Spring Boot

▶ 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

Page 42: Spring and Spring Boot

42

Java EE vs Spring

Page 43: Spring and Spring Boot

43

Not really…

Page 44: Spring and Spring Boot

▶ 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

Page 45: Spring and Spring Boot

▶ The Spring framework is divided into modules

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

Spring Framework

45

Page 46: Spring and Spring Boot

▶ 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

Page 47: Spring and Spring Boot

-

Beans

47

Page 48: Spring and Spring Boot

▶ 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

Page 49: Spring and Spring Boot

▶ 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

Page 50: Spring and Spring Boot

▶ 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

Page 51: Spring and Spring Boot

▶ 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

Page 52: Spring and Spring Boot

▶ 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

Page 53: Spring and Spring Boot

▶ 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

Page 54: Spring and Spring Boot

-

Dependency Injection (DI)

54

Page 55: Spring and Spring Boot

▶ 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

Page 56: Spring and Spring Boot

▶ 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

Page 57: Spring and Spring Boot

▶ 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

Page 58: Spring and Spring Boot

▶ 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

Page 59: Spring and Spring Boot

Microservice Frameworks

59

Page 60: Spring and Spring Boot

Frameworks, Frameworks, Frameworks

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

Page 61: Spring and Spring Boot

-

Microprofile.io

https://microprofile.io/

61

Page 62: Spring and Spring Boot

Enterprise Java for a Microservices Architecture

62

Page 63: Spring and Spring Boot

GraalVM

63

Page 64: Spring and Spring Boot

GraalVM

64

Page 65: Spring and Spring Boot

GraalVM

65

Page 66: Spring and Spring Boot

-

Spring Boot

66

Page 67: Spring and Spring Boot

67

Page 68: Spring and Spring Boot

▶ 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

Page 69: Spring and Spring Boot

▶ 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

Page 70: Spring and Spring Boot

▶ 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

Page 71: Spring and Spring Boot

▶ Spring Boot Website

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

▶ Reference Documentation

▶ Spring Initializer

▶ https://start.spring.io/

On your mark, ready, GO!

71

Page 72: Spring and Spring Boot

▶ 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

Page 73: Spring and Spring Boot

▶ 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

Page 74: Spring and Spring Boot

▶ 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

Page 75: Spring and Spring Boot

▶ 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

Page 76: Spring and Spring Boot

▶ 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

Page 77: Spring and Spring Boot

▶ 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