Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based...

35
Spring Petr Kˇ remen [email protected] Winter Term 2018 Petr Kˇ remen ([email protected]) Spring Winter Term 2018 1 / 35

Transcript of Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based...

Page 1: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring

Petr Kremen

[email protected]

Winter Term 2018

Petr Kremen ([email protected]) Spring Winter Term 2018 1 / 35

Page 2: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Contents

1 Business Logic

2 Dependency Injection

3 Spring Container Features

4 Spring 5

5 Spring Modules

Petr Kremen ([email protected]) Spring Winter Term 2018 2 / 35

Page 3: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Business Logic

Business Logic

Petr Kremen ([email protected]) Spring Winter Term 2018 3 / 35

Page 4: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Business Logic

Spring and Java EE

Job Trends by indeed.com

Petr Kremen ([email protected]) Spring Winter Term 2018 4 / 35

Page 5: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Business Logic

Spring Framework Highlights

pros

Dependency Injection

Convention over Configuration

Many Components for desk-top/web/enterpriseapplicationdevelopment

Modular , i.e. individualSpring componentscan be used andcombined withother frameworks

Open-Source, POJO-Based

cons

Not part of the Java EE stack

Examples

Examples from this lecture canbe found athttps://gitlab.fel.cvut.cz/ear/spring-example.

Petr Kremen ([email protected]) Spring Winter Term 2018 5 / 35

Page 6: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Business Logic

Spring and EJB

both technologies provide enterprise container with DI andtransactions,

EJB is a part of Java EE stack, it is a standard, supportinghigh-availability, clustering.

Spring is a feature-rich alternative to EJB with many extensions cf.EJB, e.g. @Configurable

A comparison is at https://zeroturnaround.com/rebellabs/spring-and-java-ee-head-to-head

Petr Kremen ([email protected]) Spring Winter Term 2018 6 / 35

Page 7: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Dependency Injection

Petr Kremen ([email protected]) Spring Winter Term 2018 7 / 35

Page 8: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Dependency Injection Motivation I

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.

Petr Kremen ([email protected]) Spring Winter Term 2018 8 / 35

Page 9: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

DI using XML

SchoolInformationSystem.java

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

public class SchoolInformationSystem {private CourseRepository repository;

public static void main(String[] args) {final String C= "classpath*:application-config.xml";

final ApplicationContext ac= new ClassPathXmlApplicationContext(C);

SchoolInformationSystem s = ac.getBean(SchoolInformationSystem.class

);

System.out.println(s.repository.getName());}

}

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 ...

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

}

application-config.xml

<?xml version="1.0" encoding="UTF-8"?><beans ...><beanid="SchoolInformationSystem"class="cz.cvut.kbss.ear.

spring_example.SchoolInformationSystem"scope="singleton"><property name="repository"ref="CourseRepository"/>

</bean><bean id="CourseRepository"class="cz.cvut.kbss.ear.

spring_example.InMemoryCourseRepository"></bean>

</beans>

Petr Kremen ([email protected]) Spring Winter Term 2018 9 / 35

Page 10: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Dependency Injection (DI) and Inversion of Control (IoC)

Dependency Injection

The application lifecycle is controlled by the container which is responsiblefor delivering correct implementation of the given bean

Inversion of Control

The programmed application is a “library” for the generic framework thatcontrols the application lifecycle.

Hollywood Principle

Don’t call us, we’ll call you.

Petr Kremen ([email protected]) Spring Winter Term 2018 10 / 35

Page 11: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

DI using AnnotationsSchoolInformationSystem.java

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

@Componentpublic class SchoolInformationSystem {@Autowiredprivate CourseRepository repository;

public static void main(String[] args) {final String C= "classpath*:application-config.xml";

final ApplicationContext ac= new ClassPathXmlApplicationContext(C);

SchoolInformationSystem s = ac.getBean(SchoolInformationSystem.class

);

System.out.println(s.repository.getName());}

}

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"; }

}

application-config.xml

<?xml version="1.0" encoding="UTF-8"?><beans ... ><context:annotation-config/><context:component-scan base-package

="cz.cvut.kbss.ear.spring_example"/></beans>

Petr Kremen ([email protected]) Spring Winter Term 2018 11 / 35

Page 12: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

DI with JSR 330 annotations and bean disambiguation

JSR 330: Dependency Injection for Java

is a part of Java EE Web Profile. Spring supports JSR 330 annotations.

SchoolInformationSystem.java

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

@Namedpublic class SchoolInformationSystem {@Injectprivate 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 ...

@Namedpublic class InMemoryCourseRepositoryimplements CourseRepository {public String getName() { return "In-memorycourse repository"; }

}

AnotherInMemoryCourseRepository.java

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

@Named("repository")public class AnotherInMemoryCourseRepositoryimplements CourseRepository {public String getName() { return "AnotherIn-memory course repository"; }

}

Petr Kremen ([email protected]) Spring Winter Term 2018 12 / 35

Page 13: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Related Dependency Technologies

Dependency Injection for Java (JSR 330)

dependency mechanism(partially) implemented in Spring

∈ Java EE Web Profile

Context Dependency Injection (CDI) (JSR 299)

definition of bean scopesnot implemented in Spring

∈ Java EE Web Profile

Petr Kremen ([email protected]) Spring Winter Term 2018 13 / 35

Page 14: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Spring Bean Scopes

singleton a single bean instance per Spring IoC container

prototype a new bean instance each time when requested

request a single bean instance per HTTP request

session a single bean instance per HTTP session

globalSession a single bean instance per global HTTP session

global HTTP session

A session shared accross multiple portlets in a portlet application.

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

Petr Kremen ([email protected]) Spring Winter Term 2018 14 / 35

Page 15: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Spring Bean Scopes – Prototype

SchoolInformationSystem.java

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

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

@Autowiredprivate CourseRepositorysecondRepository;

...

public static void main(String[] args) {...// injected SchoolInformationSystem s;System.out.println(s.repository == s.secondRepository

);}

}

CourseRepository.java

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

}

AnotherInMemoryCourseRepository.java

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

@Component("repository")@Scope("prototype")public class AnotherInMemoryCourseRepositoryimplements CourseRepository {public String getName() { return "AnotherIn-memory course repository"; }

}

prints “false”

Petr Kremen ([email protected]) Spring Winter Term 2018 15 / 35

Page 16: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Spring Bean Scopes – Singleton

SchoolInformationSystem.java

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

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

@Autowiredprivate CourseRepositorysecondRepository;

...

public static void main(String[] args) {...// injected SchoolInformationSystem s;System.out.println(s.repository == s.secondRepository

);}

}

CourseRepository.java

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

}

AnotherInMemoryCourseRepository.java

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

@Component("repository")@Scope("singleton")public class AnotherInMemoryCourseRepositoryimplements CourseRepository {public String getName() { return "AnotherIn-memory course repository"; }

}

prints “true”

Petr Kremen ([email protected]) Spring Winter Term 2018 16 / 35

Page 17: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

Dependency management for non-Spring objects

sometimes Spring cannot manage bean lifecycle, but needs to injectinto it

objects of other frameworks need not be ready for being managed bySpringJPA entities – based on OO paradigm, objects should encapsulate bothstate and operations

annotation @Configurable denotes classes, objects of which arenot managed by Spring, yet can inject Spring-managed objects

byte-code instrumentation (aspect weaving)

Load-Time weaving (java agent)Compile-time weaving (aspect compiler)

Petr Kremen ([email protected]) Spring Winter Term 2018 17 / 35

Page 18: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Dependency Injection

@Configurable – Example

@Configurable(preConstruction=true)@Entitypublic class User {

@Column(length=40, nullable=false)private String password;

@Column(length=40, nullable=false)private String salt;

@Autowiredprivate transient HashProvider provider;...public void setPassword(String password) {this.password = provider.computeHash(password + salt + "/* long string */");

}}

Petr Kremen ([email protected]) Spring Winter Term 2018 18 / 35

Page 19: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Spring Container Features

Petr Kremen ([email protected]) Spring Winter Term 2018 19 / 35

Page 20: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Transactions

public interface UserService {

@Transactional(readOnly=true)public List<UserDTO> getAllUsers();

@Transactionalpublic UserDTO saveUser(UserDTO user, Stringpassword);

@Transactional(readOnly=true)public UserDTO getUserByUserName(String name);

@Transactionalpublic void deleteUser(Long id);...}

<!-- from the file ’context.xml’ --><?xml version="1.0" encoding="UTF-8"?><beans ...>

<bean id="userService"class="....UserService"/>

<tx:annotation-driventransaction-manager="txManager"/><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- (this dependency is definedsomewhere else) -->

<property name="dataSource"ref="dataSource"/>

</bean></beans>

transactions configurable through XML/annotations

global/local transactions

wraps multiple transaction APIs – JDBC, JTA, JPA, ...

Petr Kremen ([email protected]) Spring Winter Term 2018 20 / 35

Page 21: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Transaction Flow

source: Spring documentation,docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html

Petr Kremen ([email protected]) Spring Winter Term 2018 21 / 35

Page 22: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Transaction Propagation

We can control, whether and how the transactional execution of themethod should be supported

@Transactional(propagation=...

REQUIRED

SUPPORTS

MANDATORY

REQUIRES NEW

NOT SUPPORTED

NEVER

NESTED

Petr Kremen ([email protected]) Spring Winter Term 2018 22 / 35

Page 23: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Transaction Isolation

We can control the transaction isolation level

@Transactional(isolation=...

DEFAULT

READ UNCOMMITTED

READ COMMITTED

REPEATABLE READ

SERIALIZABLE

Petr Kremen ([email protected]) Spring Winter Term 2018 23 / 35

Page 24: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Other Transaction attributes

rollbackFor (and other similar) – which exception hierarchiescause rollback (RuntimeException and Error by default)

readOnly – true/false – readonly transactions can be optimized inruntime

timeout

transactionManager

Petr Kremen ([email protected]) Spring Winter Term 2018 24 / 35

Page 25: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Distributed Transactions

Petr Kremen ([email protected]) Spring Winter Term 2018 25 / 35

Page 26: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Spring and Persistence

1 use standard JPA configuration through persistence.xml andload it by Spring

reuse of existing configurationtwo XML configuration types

2 configure JPA using Spring

one type of XML configuration/annotationsone more dependency on Spring ...

Petr Kremen ([email protected]) Spring Winter Term 2018 26 / 35

Page 27: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

JPA Configuration

<bean id="entityManagerFactory"class="org.springframework.orm.jpa.

LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"/><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.

HibernateJpaVendorAdapter"><property name="databasePlatform"value="${jpa.platform}"/>

<property name="generateDdl" value="true"/><property name="showSql" value="true"/>

</bean></property><property name="packagesToScan" value="cz.xy" />

</bean>

Petr Kremen ([email protected]) Spring Winter Term 2018 27 / 35

Page 28: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Container Features

Security

@Transactional(propagation=Propagation.REQUIRED)public interface UserService {

@Secured("ROLE_ADMIN")public UserDTO save(UserDTO userDTO, String password,

Boolean isAdmin, Boolean isEditor);

@Secured("ROLE_ADMIN")public void removeById(Long id);...}

Method Access using Annotations

Petr Kremen ([email protected]) Spring Winter Term 2018 28 / 35

Page 29: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring 5

Spring 5

Petr Kremen ([email protected]) Spring Winter Term 2018 29 / 35

Page 30: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring 5

Spring 5 Features

built on Java SE 8, Java EE 7

@Nullable and @NotNull – compile time validation of null values

Kotlin support – functional programming (web endpoints/beanregistration).

reactive programming – “async logic without callbacks” (WebFlux)

Petr Kremen ([email protected]) Spring Winter Term 2018 30 / 35

Page 31: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring 5

Reactive Programming – WebFlux

Annotation-based

@RestControllerpublic class BookController {@GetMapping("/book/{id}")Mono<Book> findById(@PathVariable Stringid) {return this.repository.findOne(id);

}// Plumbing code omitted for brevity

}

Mono (like CompletableFuture) –asynchronous response

repository has support for async.responses too

Functional programming-based

public class BookHandler {public Mono<ServerResponse>getBook(ServerRequest request) {return repository.getBook(request.pathVariable("id")).then(book -> ServerResponse.ok()

.contentType(APPLICATION_JSON)

.body(fromObject(book))).otherwiseIfEmpty(ServerResponse.notFound().build()

);}// Plumbing code omitted for brevity

}

BookHandler handler = new BookHandler();

RouterFunction<ServerResponse> personRoute =route(GET("/books/{id}").and(accept(APPLICATION_JSON)),handler::getBook));

Petr Kremen ([email protected]) Spring Winter Term 2018 31 / 35

Page 32: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Modules

Spring Modules

Petr Kremen ([email protected]) Spring Winter Term 2018 32 / 35

Page 33: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Modules

Spring Landscape

source: Spring documentation,docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html

Petr Kremen ([email protected]) Spring Winter Term 2018 33 / 35

Page 34: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Modules

Selected Spring Modules

Spring Core framework core

Spring ORM JPA integration and ORM

Spring MVC MVC web framework

Spring Test testing support

Spring Security application security support

Spring Social social network support – e.g. Facebook, Twitter, LinkedIn

Spring Integration System Integration (Enterprise Integration Patterns)

Petr Kremen ([email protected]) Spring Winter Term 2018 34 / 35

Page 35: Spring · Spring components can be used and combined with other frameworks Open-Source, POJO-Based cons Not part of the Java EE stack Examples Examples from this lecture can be found

Spring Modules

Resources

SpringSourcehttp://www.springsource.org

Spring Framework – Documentationhttp://static.springsource.org/spring/docs/4.2.x/spring-framework-reference/html

Spring (WPA lecture)https://cw.fel.cvut.cz/wiki/_media/courses/a7b39wpa/spring1.pdf

Petr Kremen ([email protected]) Spring Winter Term 2018 35 / 35