0% found this document useful (0 votes)
5 views39 pages

Lecture 04 Spring S

The document provides an overview of the Spring Framework, covering key topics such as business logic, dependency injection, Spring container features, and Spring Boot. It discusses the advantages and disadvantages of Spring compared to Java EE, as well as various dependency injection mechanisms and bean scopes. Additionally, it highlights transaction management and persistence configuration in Spring applications.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views39 pages

Lecture 04 Spring S

The document provides an overview of the Spring Framework, covering key topics such as business logic, dependency injection, Spring container features, and Spring Boot. It discusses the advantages and disadvantages of Spring compared to Java EE, as well as various dependency injection mechanisms and bean scopes. Additionally, it highlights transaction management and persistence configuration in Spring applications.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Spring

Petr Křemen, Martin Ledvinka

KBSS FEL ČVUT

Winter Term 2019

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 1 / 39
Contents

1 Business Logic

2 Dependency Injection

3 Spring Container Features

4 Spring 5

5 Spring Modules

6 Spring Boot

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 2 / 39
Business Logic

Business Logic

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 3 / 39
Business Logic

Spring and Java EE


Job Trends by indeed.com

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 4 / 39
Business Logic

Spring Framework Highlights

pros cons
Dependency Injection Not part of the Java EE stack
Convention over Configuration
Examples
Many Components for desk-
top/web/enterprise Examples from this lecture can
application be found at
development https://gitlab.fel.cvut.
cz/ear/spring-example.
Modular , i.e., individual
Spring components
can be used and
combined with
other frameworks
Open-Source, POJO-Based

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 5 / 39
Business Logic

Spring and EJB

Both technologies provide enterprise container with DI, IoC,


transactions and other relevant features
EJB is a part of Java EE stack, it is a standard, supporting
high-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 Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 6 / 39
Dependency Injection

Dependency Injection

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 7 / 39
Dependency Injection

Dependency Injection Reminder


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 which


repository implementation to use
change in implementation requires client code change.
change in configuration requires client code change.

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 8 / 39
Dependency Injection

DI using XML
SchoolInformationSystem.java InMemoryCourseRepository.java
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... import ...

public class SchoolInformationSystem { public class InMemoryCourseRepository


private CourseRepository repository; implements CourseRepository {
} public String getName() { return
"In-memory course repository"; }
}
CourseRepository.java
package cz.cvut.kbss.ear.spring_example;
public interface CourseRepository {
public String getName() { return name; }
}

application-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="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 Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 9 / 39
Dependency Injection

DI using Annotations

SchoolInformationSystem.java InMemoryCourseRepository.java
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... import ...

@Component @Component
public class SchoolInformationSystem { public class InMemoryCourseRepository
@Autowired implements CourseRepository {
private CourseRepository repository; public String getName() { return
} "In-memory course repository"; }
}
CourseRepository.java
package cz.cvut.kbss.ear.spring_example;
public interface CourseRepository {
public String getName() { return name; }
}

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 10 / 39
Dependency Injection

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

Dependency Injection
Component lifecycle is controlled by the container which is responsible for
delivering correct implementation of the given bean.

Inversion of Control
The programmed application is a “library” for the generic framework that
controls the application lifecycle.

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

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 11 / 39
Dependency Injection

Dependency Injection

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 12 / 39
Dependency Injection

Inversion of Control

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 13 / 39
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 scopes
Not implemented in Spring
∈ Java EE Web Profile

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 14 / 39
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 InMemoryCourseRepository.java
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... import ...

@Named @Named
public class SchoolInformationSystem { public class InMemoryCourseRepository
@Inject implements CourseRepository {
private CourseRepository repository; public String getName() { return "In-memory
course repository"; }
... }
}
AnotherInMemoryCourseRepository.java
CourseRepository.java
package cz.cvut.kbss.ear.spring_example;
package cz.cvut.kbss.ear.spring_example; import ...
public interface CourseRepository {
public String getName() { return name; } @Named("repository")
} public class AnotherInMemoryCourseRepository
implements CourseRepository {
public String getName() { return "Another
In-memory course repository"; }
}

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 15 / 39
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 Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 16 / 39
Dependency Injection

Spring Bean Scopes – Prototype


SchoolInformationSystem.java CourseRepository.java
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... public interface CourseRepository {
public String getName() { return name; }
@Component }
@Scope("singleton")
public class SchoolInformationSystem {
@Autowired
AnotherInMemoryCourseRepository.java
private CourseRepository repository;
package cz.cvut.kbss.ear.spring_example;
@Autowired import ...
private CourseRepository
secondRepository; @Component("repository")
... @Scope("prototype")
public class AnotherInMemoryCourseRepository
public static void main(String[] args) { implements CourseRepository {
... public String getName() { return "Another
// injected SchoolInformationSystem s; In-memory course repository"; }
System.out.println( }
s.repository == s.secondRepository
);
}
}

prints “false”

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 17 / 39
Dependency Injection

Spring Bean Scopes – Singleton


SchoolInformationSystem.java CourseRepository.java
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... public interface CourseRepository {
public String getName() { return name; }
@Component }
@Scope("singleton")
public class SchoolInformationSystem {
@Autowired
AnotherInMemoryCourseRepository.java
private CourseRepository repository;
package cz.cvut.kbss.ear.spring_example;
@Autowired import ...
private CourseRepository
secondRepository; @Component("repository")
... @Scope("singleton")
public class AnotherInMemoryCourseRepository
public static void main(String[] args) { implements CourseRepository {
... public String getName() { return "Another
// injected SchoolInformationSystem s; In-memory course repository"; }
System.out.println( }
s.repository == s.secondRepository
);
}
}

prints “true”

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 18 / 39
Dependency Injection

Dependency Injection Mechanisms


Constructor injection Setter injection
package cz.cvut.kbss.ear.spring_example; package cz.cvut.kbss.ear.spring_example;
import ... import ...

@Component @Component
public class SchoolInformationSystem { public class SchoolInformationSystem {

private CourseRepository repository; private CourseRepository repository;

@Autowired @Autowired
public public void setRepository(CourseRepository
SchoolInformationSystem(CourseRepository repository) {
repository) { this.repository = repository;
this.repository = repository; }
} }
}

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

@Component
public class SchoolInformationSystem {

@Autowired
private CourseRepository repository;
}

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 19 / 39
Dependency Injection

Dependency management for non-Spring objects

Sometimes Spring cannot manage bean lifecycle, but needs to inject


into it
Objects of other frameworks need not be ready for being managed by
Spring
JPA entities – based on OO paradigm, objects should encapsulate both
state and operations
Annotation @Configurable denotes classes, objects of which are
not managed by Spring, yet can inject Spring-managed objects
Byte-code instrumentation (aspect weaving)
Load-time weaving (java agent)
Compile-time weaving (aspect compiler)
Same mechanism used for declarative transactions (see later)

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 20 / 39
Dependency Injection

@Configurable – Example
@Configurable
@Entity
public class User {

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

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

@Autowired
private transient HashProvider provider;
...
public void setPassword(String password) {
this.password = provider.computeHash(
password + salt + "/* long string */");
}
}
Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 21 / 39
Spring Container Features

Spring Container Features

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 22 / 39
Spring Container Features

Declarative Transactions
@Component
public class UserService {

@Autowired
private UserDao userDao;

@Transactional(readOnly=true)
public List<UserDTO> findAll() {
// implementation
}

@Transactional
public UserDTO persist(UserDTO user, String password) {
// implementation
}

@Transactional(readOnly=true)
public UserDTO findByUsername(String name) {
// implementation
}

// Other methods
}

Transactions configurable through XML/annotations


Global/local transactions
Wraps multiple transaction APIs – JDBC, JTA, JPA, ...
Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 23 / 39
Spring Container Features

Transaction Flow

Source:
docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 24 / 39
Spring Container Features

Transaction Propagation

We can control, whether and how the transactional execution of the


method should be supported
@Transactional(propagation=...

MANDATORY
NESTED
NEVER
NOT SUPPORTED
REQUIRED – default
REQUIRES NEW
SUPPORTS

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 25 / 39
Spring Container Features

Other Transaction Attributes

isolation – transaction isolation level


rollbackFor (and other similar) – which exception hierarchies
cause rollback (RuntimeException and Error by default)
readOnly – true/false – readonly transactions can be optimized in
runtime
timeout
transactionManager

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 26 / 39
Spring Container Features

Distributed Transactions

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 27 / 39
Spring Container Features

Spring and Persistence

1 Use standard JPA configuration through persistence.xml and


load it by Spring
Reuse of existing configuration
Two XML configuration types
2 Configure JPA using Spring
One type of XML configuration/annotations
One more dependency on Spring...

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 28 / 39
Spring Container Features

JPA Configuration
@Configuration
@PropertySources({@PropertySource("classpath:jpa.properties"),
@PropertySource("classpath:jdbc.properties")})
@ComponentScan(basePackages = "cz.cvut.kbss.ear.eshop.dao")
public class PersistenceConfig {
@Autowired
private final Environment environment;

@Bean
public DataSource dataSource() {
final BoneCPDataSource ds = new BoneCPDataSource();
ds.setDriverClass(environment.getRequiredProperty("jdbc.driverClassName"));
ds.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
ds.setUsername(environment.getRequiredProperty("jdbc.username"));
ds.setPassword(environment.getRequiredProperty("jdbc.password"));
return ds;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource ds) {
final LocalContainerEntityManagerFactoryBean emf = new
LocalContainerEntityManagerFactoryBean();
emf.setDataSource(ds);
emf.setJpaVendorAdapter(new EclipseLinkJpaVendorAdapter());
emf.setPackagesToScan("cz.cvut.kbss.ear.eshop.model");

final Properties props = new Properties();


props.setProperty("databasePlatform", environment.getRequiredProperty("jpa.platform"));
emf.setJpaProperties(props);
return emf;
}

Petr Křemen, Martin Ledvinka


@Bean(name (KBSS FEL ČVUT)
= "txManager") Spring Winter Term 2019 29 / 39
Spring Container Features

Security

@Transactional
public class UserService {

@Autowired
private UserDao dao;

@Secured("ROLE_ADMIN")
public void persist(UserDto user, String password, Boolean isAdmin) {
// Implementation
}

@Secured("ROLE_ADMIN")
public void removeById(Long id) {
// Implementation
}
}

Method access control using annotations


More on this in weeks 7 and 10

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 30 / 39
Spring 5

Spring 5

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 31 / 39
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/bean
registration).
Reactive programming – “async logic without callbacks” (WebFlux)

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 32 / 39
Spring Modules

Spring Modules

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 33 / 39
Spring Modules

Spring Landscape

source: Spring documentation,


docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 34 / 39
Spring Modules

Selected Spring Modules

Spring Core framework core


Spring ORM JPA integration and ORM
Spring MVC MVC web framework, REST controllers
Spring Test testing support
Spring Security application security support
Spring Data access to data – paging, filtering, map-reduce
Spring Integration enterprise integration patterns – gateways, channels,
adapters
Spring Boot

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 35 / 39
Spring Boot

Spring Boot

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 36 / 39
Spring Boot

Spring Boot

Spring module for rapid standalone application development


Greatly simplifies configuration and deployment
Taking convention over configuration to the next level
Composed annotations group common annotations
Sensible configuration defaults
Automatic classpath scan for beans
Package as jar for simple startup – embedded application server
(Tomcat or Jetty) for web applications
Externalized configuration – application.properties

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 37 / 39
Spring Boot

Spring Boot II

To simplify configuration even more, starter projects containing


common dependencies are provided
spring-boot-starter-parent – parent Maven project
spring-boot-starter-data-jpa
spring-boot-starter-web
spring-boot-starter-security
...
Test extensions allowing to isolate tested components
@DataJpaTest, @SpringBootTest
Automatic creation of default beans
@ConditionalOnMissingBean
ObjectMapper, DataSource, TransactionManager
TestRestTemplate for tests

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 38 / 39
Spring Boot

Resources

Spring home
https://spring.io/
Spring Framework – Documentation
https://docs.spring.io/spring/docs/current/
spring-framework-reference/index.html
Spring Boot – Documentation
https://docs.spring.io/spring-boot/docs/current/
reference/html/
Spring (WPA lecture)
https://cw.fel.cvut.cz/wiki/_media/courses/
a7b39wpa/spring1.pdf

Petr Křemen, Martin Ledvinka (KBSS FEL ČVUT) Spring Winter Term 2019 39 / 39

You might also like