spring - cw.fel.cvut.cz

31
Spring Miroslav Blaˇ sko, Bogdan Kostov, Martin Ledvinka KBSS FEL CTU in Prague Winter Term 2021 Miroslav Blaˇ sko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague) Spring Winter Term 2021 1 / 29

Upload: others

Post on 25-Dec-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Spring - cw.fel.cvut.cz

Spring

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka

KBSS FEL CTU in Prague

Winter Term 2021

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 1 / 29

Page 2: Spring - cw.fel.cvut.cz

Contents

1 Introduction

2 Dependency Injection - Revisited

3 Spring Beans

4 Spring Transaction ManagementProxy Design Pattern

5 Other Commonly Used Spring FeaturesDemo E-Shop Application

6 Tasks

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 2 / 29

Page 3: Spring - cw.fel.cvut.cz

Introduction

Introduction

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 3 / 29

Page 4: Spring - cw.fel.cvut.cz

Introduction

Seminar Topic

In this seminar we will learn to use Spring and its main features:

Dependency Injection (DI)

Transaction management

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 4 / 29

Page 5: Spring - cw.fel.cvut.cz

Dependency Injection - Revisited

Dependency Injection - Revisited

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 5 / 29

Page 6: Spring - cw.fel.cvut.cz

Dependency Injection - Revisited

Definition and Sequence Example

Dependency Injection

Component lifecycle is controlled by the container which is responsible fordelivering correct implementation of the given dependency.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 6 / 29

Page 7: Spring - cw.fel.cvut.cz

Dependency Injection - Revisited

Plain Java code vs DI

package cz.cvut.kbss.ear.spring_example;import ...

public class SchoolInformationSystem {

private CourseRepository repository= new InMemoryCourseRepository();

public static void main(String[] args) {SchoolInformationSystem main = new SchoolInformationSystem();System.out.println(main.repository.getName());

}}

The client code (SchoolInformationSystem) itself decides whichrepository implementation to use

change in implementation requires client code change.

change in configuration requires client code change.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 7 / 29

Page 8: Spring - cw.fel.cvut.cz

Dependency Injection - Revisited

DI using Annotations

SchoolInformationSystem.java

package cz.cvut.kbss.ear.spring_example;import ...

@Componentpublic class SchoolInformationSystem {@Autowiredprivate CourseRepository repository;

}

CourseRepository.java

package cz.cvut.kbss.ear.spring_example;public interface CourseRepository {public String getName() { return name; }

}

InMemoryCourseRepository.java

package cz.cvut.kbss.ear.spring_example;import ...

@Componentpublic class InMemoryCourseRepositoryimplements CourseRepository {public String getName() { return"In-memory course repository"; }

}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 8 / 29

Page 9: Spring - cw.fel.cvut.cz

Spring Beans

Spring Beans

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 9 / 29

Page 10: Spring - cw.fel.cvut.cz

Spring Beans

Bean Declaration

Bean declaration tells Spring from which classes to create beans. We willlearn about two ways of bean declaration:

Bean creation through annotated classes

Bean creation with a factory method

Spring needs to know where to look for bean declarations. With SpringBoot, it scans the package of the main application class and all itssub-packages.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 10 / 29

Page 11: Spring - cw.fel.cvut.cz

Spring Beans

Bean Declaration - Annotated Class

A bean can be declared using an annotation on a class. Annotations usedfor declaration of beans in this way are:

@Component

@Configuration

@Repository

@Service

etc.

Code example:

package cz.cvut.kbss.ear.spring_example;import ...

@Componentpublic class InMemoryCourseRepository implements CourseRepository {public String getName() { return "In-memory course repository"; }

}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 11 / 29

Page 12: Spring - cw.fel.cvut.cz

Spring Beans

Bean Declaration - Factory method

A bean factory method should be implemented in a configuration bean.The method should be annotated with the @Bean annotation and it shouldreturn the bean. The method’s parameters will be injected if possible.Code example:

@Configuration // is this a bean? Yes it is.public class RepositoryConfiguration{@Beanpublic InMemoryCourseRepository createInMemoryRepository() {

return new InMemoryCourseRepository();}

}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 12 / 29

Page 13: Spring - cw.fel.cvut.cz

Spring Beans

Spring Bean Scopes

Scopes define the life cycle of a bean

singleton a single bean instance per a Spring IoC container (thedefault scope)

prototype a new bean instance every time when requested (e.g.,injected during creation of another bean)

request a single bean instance per an HTTP request

session a single bean instance per an HTTP session

globalSession a single bean instance per a global HTTP session

Code example specifying the scope of a bean:

@Component@Scope("singleton")public class SchoolInformationSystem {@Autowiredprivate CourseRepository repository;

}

Spring allows custom scope definition (e.g. JSF 2 Flash scope)

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 13 / 29

Page 14: Spring - cw.fel.cvut.cz

Spring Beans

Bean Injection

During creation, beans are injected with the declared dependencies (mustbe also beans). To declare a dependency in Spring use the annotation:

@Autowired

Code example:

package cz.cvut.kbss.ear.spring_example;import ...

@Componentpublic class SchoolInformationSystem {@Autowiredprivate CourseRepository repository;

}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 14 / 29

Page 15: Spring - cw.fel.cvut.cz

Spring Beans

Injecting Entity Manager

The entity manager is injected using the @PersistenceContextannotation (JPA).Code example:

@Repositorypublic class CartDao {@PersistenceContextprivate EntityManager em;...

}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 15 / 29

Page 16: Spring - cw.fel.cvut.cz

Spring Transaction Management

Spring Transaction Management

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 16 / 29

Page 17: Spring - cw.fel.cvut.cz

Spring Transaction Management

Transaction Management Annotations

Spring provides means to declaratively manage business transactions.The following annotations work in conjunction with JPA.

@Transactional - on methods and classes, wraps a method in atransaction

@EnableTransactionManagement - enabling declarativetransaction support, enabled by default in Spring Boot

Code example:

@Servicepublic class CartService {@Transactionalpublic void addItem(Cart cart, CartItem toAdd) {...

}}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 17 / 29

Page 18: Spring - cw.fel.cvut.cz

Spring Transaction Management Proxy Design Pattern

Proxy Design Pattern

Question Is the class of CartService bean CartService?

Answer No, it is not. It is a subclass of CartService.

Proxy Design Pattern

Spring implements transaction management using the Proxy DesignPattern on beans. The CartService is sub-classed in the backgroundto enable wrapping transactional method calls with code managing thetransactions.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 18 / 29

Page 19: Spring - cw.fel.cvut.cz

Spring Transaction Management Proxy Design Pattern

Proxy Design Pattern

Question Is the class of CartService bean CartService?

Answer No, it is not. It is a subclass of CartService.

Proxy Design Pattern

Spring implements transaction management using the Proxy DesignPattern on beans. The CartService is sub-classed in the backgroundto enable wrapping transactional method calls with code managing thetransactions.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 18 / 29

Page 20: Spring - cw.fel.cvut.cz

Spring Transaction Management Proxy Design Pattern

Proxy Design Pattern

Question Is the class of CartService bean CartService?

Answer No, it is not. It is a subclass of CartService.

Proxy Design Pattern

Spring implements transaction management using the Proxy DesignPattern on beans. The CartService is sub-classed in the backgroundto enable wrapping transactional method calls with code managing thetransactions.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 18 / 29

Page 21: Spring - cw.fel.cvut.cz

Spring Transaction Management Proxy Design Pattern

Proxy Design Pattern - Java Code Example

Calculator.java

public class Calculator{public int add(int a, int b){return a + b;

}

public int subtract(int a, int b){return a - b;

}}

CalculatorLoggerProxy.java

public class CalculatorLoggerProxy extendsCalculator{private static final Logger LOG ...@Overridepublic int add(int a, int b){int ret = super.add(a,b);LOG.debug("{} + {} = {}", a, b, ret);return ret;

}

@Overridepublic int subtract(int a, int b){int ret = super.subtract(a,b);LOG.debug("{} - {} = {}", a, b, ret);return ret;

}}

Some observations:

CalculatorLoggerProxy is also a Calculator

Extends execution by adding pre- and post-processing code

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 19 / 29

Page 22: Spring - cw.fel.cvut.cz

Other Commonly Used Spring Features

Other Commonly Used SpringFeatures

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 20 / 29

Page 23: Spring - cw.fel.cvut.cz

Other Commonly Used Spring Features

Annotation based Spring Configuration

@ComponentScan searching for Spring beans among classes in agiven package

@ComponentScan without argument scans the current package andall its sub-packages

@Import composing Spring configuration

Searching for beans:

@Configuration@ComponentScan(basePackages = "cz.cvut.kbss.ear.eshop.dao")public class PersistenceConfig {...}

Importing configuration:

@Configuration@Import( {PersistenceConfig.class})public class AppConfig {...}

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 21 / 29

Page 24: Spring - cw.fel.cvut.cz

Other Commonly Used Spring Features Demo E-Shop Application

Spring Configuration in E-shop

The E-Shop application is implemented using Spring Boot, which hasmany benefits over plain Spring:

Provides a single Maven dependency which includes profiles ofdifferent spring packages commonly used together

Provides a simpler Maven build configuration

A Maven plugin which builds the application into a JAR with anembedded application server for rapid deployment

Requires minimal application configuration compared to Spring

Contains a lot of sensible defaults which just work in most cases

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 22 / 29

Page 25: Spring - cw.fel.cvut.cz

Tasks

Tasks

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 23 / 29

Page 26: Spring - cw.fel.cvut.cz

Tasks

Syncing Your Fork

1 Make sure your local copy git repository is configured correctly and allchanges are committed (git status - your branch is up to date,nothing to commit).

2 Fetch branches and commits from the upstream repository(EAR/B211-eshop)

git fetch upstream

3 Check out local branch corresponding to the task branch

git checkout -b b211-seminar-05-task

4 Merge changes from the corresponding upstream branch

git merge upstream/b211-seminar-05-task

5 Do your task6 Push the solution to your fork

git push origin b211-seminar-05-task

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 24 / 29

Page 27: Spring - cw.fel.cvut.cz

Tasks

Task 1 – Configuration of Persistence Layer (1 point)

1 Declare missing bean declarations and injections.

Some of the classes in the dao package should be declared as beansbut they are not. Declare them properly.In the dao package, there is also one dependency injection which isnot declared properly. Fix it.Hint: @Repository, @PersistenceContext

2 Create a prototype bean of type java.util.Date.

Hint: @Configuration, @Bean

Hint: Use tests to help you debug the issues.

Acceptance criteria: All enabled tests are passing.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 25 / 29

Page 28: Spring - cw.fel.cvut.cz

Tasks

Task 2 – Implementation of a Service (1 point)

1 Remove the @Disabled annotation from CartServiceTest andverify that tests are now failing

2 Implement CartService that allows to

Add specific items to a cartRemove specific items from a cartAmount of products available in stock is correctly adjusted after everyadd/remove operationCartService class must be declared as a Spring beanInject beans necessary to implement the service methods (DAO)

3 Make sure that service methods are transactional

4 Hint: @Service

5 Acceptance criteria: Transactional processing is configured properlyand all tests are passing.

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 26 / 29

Page 29: Spring - cw.fel.cvut.cz

The End

The End

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 27 / 29

Page 30: Spring - cw.fel.cvut.cz

The End

The End

Thank You

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 28 / 29

Page 31: Spring - cw.fel.cvut.cz

The End

Resources

https://docs.spring.io/spring-boot/docs/current/reference/html/

Miroslav Blasko, Bogdan Kostov, Martin Ledvinka (KBSS FEL CTU in Prague)Spring Winter Term 2021 29 / 29