Spring on Java 8

25
© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission. Spring Framework 4 on Java 8 Juergen Hoeller

description

Speaker: Juergen Hoeller Spring has a track record of providing dedicated support for new Java generations in a timely fashion, and now it's right about time to go Java 8: With Spring Framework 4.0, we're providing in-depth support for all relevant OpenJDK 8 features, including lambda expressions, JSR-310 Date and Time, parameter name discovery, and java.util.concurrent enhancements. This talk will illustrate selected Java 8 features within Spring's programming model and explore the impact on application architectures.

Transcript of Spring on Java 8

Page 1: Spring on Java 8

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Spring Framework 4 on Java 8

Juergen Hoeller

Page 2: Spring on Java 8

Introducing Spring Framework 4.0 (1)● A new baseline

– Java SE 6+– Java EE 6+ (Servlet 3.0 focused, Servlet 2.5 compatible)– all deprecated packages removed– many deprecated methods removed as well

● 3rd party open source libraries– minimum versions ~ mid 2010 now– e.g. Hibernate 3.6+, Quartz 1.8+, EhCache 2.1+

Page 3: Spring on Java 8

Introducing Spring Framework 4.0 (2)● First-class support for Java 8 language and API features

– lambda expressions– method references– JSR-310 Date and Time– repeatable annotations– parameter name discovery

Page 4: Spring on Java 8

Introducing Spring Framework 4.0 (3)● A smooth out-of-the-box experience for Groovy-based Spring

applications– AOP adaptations (i.e. special handling of GroovyObject calls)– consider a Spring application with all components written in the

Groovy language instead of Java● Groovy-based bean definitions

– formerly known as the Bean Builder in Grails– now to live alongside Spring's configuration class model

Page 5: Spring on Java 8

Introducing Spring Framework 4.0 (4)● A generalized model for conditional bean definitions

– a more flexible and more dynamic variant of bean definition profiles (as known from Spring 3.1)

– can e.g. be used for smart defaulting– see Spring Boot :-)

● @Conditional with programmatic Condition implementations– can react to rich context (existing bean definitions etc)– profile support now simply a ProfileCondition impl class

Page 6: Spring on Java 8

Introducing Spring Framework 4.0 (5)● An even more powerful annotation-based component model

– custom annotations may override specific attributes of meta-annotations

– purely convention-based: use of same attribute name

@MyTransactional(readOnly=true)

@MySessionScope(scopedProxyMode=TARGET_CLASS)

Page 7: Spring on Java 8

Introducing Spring Framework 4.0 (6)● Lazy resolution proxies

– @Lazy on injection point– alternative to Provider<MyTargetType>

● Ordered injection of lists and arrays– Ordered/@Order on candidate beans– note: relative order within specific injection result

● Type matching based on full generic type– e.g. MyRepository<Customer>

Page 8: Spring on Java 8

Introducing Spring Framework 4.0 (7)● General org.springframework.messaging module

– extracted from Spring Integration– core message and channel abstractions

● WebSocket endpoint model along the lines of Spring MVC– JSR-356 but also covering SockJS and STOMP– endpoints using generic messaging patterns

● AsyncRestTemplate– based on ListenableFuture return values

Page 9: Spring on Java 8

Introducing Spring Framework 4.0 (8)● JMS 2.0

– delivery delay, JMS 2.0 createSession variants etc● JTA 1.2

– javax.transaction.Transactional annotation● JPA 2.1

– unsynchronized persistence contexts● Bean Validation 1.1

– method parameter and return value constraints

Page 10: Spring on Java 8

Spring and Common Java SE Generations● Spring 2.5 introduced Java 6 support

– JDK 1.4 – JDK 6● Spring 3.0 raised the bar to Java 5+

– JDK 5 – JDK 6● Spring 3.1/3.2: explicit Java 7 support

– JDK 5 – JDK 7● Spring 4.0 introducing explicit Java 8 support now

– JDK 6 – JDK 8

Page 11: Spring on Java 8

Spring and Common Java EE Generations● Spring 2.5 completed Java EE 5 support

– J2EE 1.3 – Java EE 5● Spring 3.0 introduced Java EE 6 support

– J2EE 1.4 – Java EE 6● Spring 3.1/3.2: strong Servlet 3.0 focus

– J2EE 1.4 (deprecated) – Java EE 6● Spring 4.0 introducing explicit Java EE 7 support now

– Java EE 5 (with JPA 2.0 feature pack) – Java EE 7

Page 12: Spring on Java 8

The State of Java 8● Delayed again...

– scheduled for GA in September 2013– now just Developer Preview in September– OpenJDK 8 GA as late as March 2014 (!)

● IDE support for Java 8 language features– IntelliJ: available since IDEA 12, released in Dec 2012– Eclipse: announced for June 2014 (!)– Spring Tool Suite: Eclipse-based beta support earlier

Page 13: Spring on Java 8

JDK 8: Initial Problems● 1.8 bytecode level

– as generated by -target 1.8 (the compiler's default)– not accepted by ASM 4.x (Spring's bytecode parsing library)– Spring Framework 4.0 comes with patched ASM 4.1 variant

● HashMap/HashSet implementation differences– different hash algorithms in use– leading to different hash iteration order– code shouldn't rely on such an order but sometimes does

Page 14: Spring on Java 8

Java 8 Lambda Conventions● Many common Spring APIs are candidates for lambdas

– through naturally following the lambda interface conventions– formerly "single abstract method" types– now "functional interfaces"

● Simple rule: interface with single method– typically callback interfaces– for a reference: Runnable, Callable

Page 15: Spring on Java 8

Lambda Conventions in Spring APIs● JdbcTemplate

– RowMapper:Object mapRow(ResultSet rs, int rowNum) throws SQLException

● JmsTemplate– MessageCreator:

Message createMessage(Session session) throws JMSException

● TransactionTemplate– TransactionCallback:

Object doInTransaction(TransactionStatus status)

Page 16: Spring on Java 8

Lambdas with Spring's JdbcTemplate (v1)JdbcTemplate jt = new JdbcTemplate(dataSource);

jt.query("SELECT name, age FROM person WHERE dep = ?", ps -> { ps.setString(1, "Sales"); }, (rs, rowNum) -> new Person(rs.getString(1), rs.getInt(2)));

Page 17: Spring on Java 8

Lambdas with Spring's JdbcTemplate (v2)JdbcTemplate jt = new JdbcTemplate(dataSource);

jt.query("SELECT name, age FROM person WHERE dep = ?", ps -> { ps.setString(1, "Sales"); }, (rs, rowNum) -> { return new Person(rs.getString(1), rs.getInt(2)); });

Page 18: Spring on Java 8

Method References with Spring's JdbcTemplatepublic List<Person> getPersonList(String department) { JdbcTemplate jt = new JdbcTemplate(this.dataSource); return jt.query("SELECT name, age FROM person WHERE dep = ?", ps -> { ps.setString(1, "Sales"); },

this::mapPerson);}

private Person mapPerson(ResultSet rs, int rowNum) throws SQLException { return new Person(rs.getString(1), rs.getInt(2));}

Page 19: Spring on Java 8

JSR-310 Date and Timeimport java.time.*;import org.springframework.format.annotation.*;

public class Customer {

// @DateTimeFormat(iso=ISO.DATE) private LocalDate birthDate;

@DateTimeFormat(pattern="M/d/yy h:mm") private LocalDateTime lastContact;}

Page 20: Spring on Java 8

Repeatable Annotations@Scheduled(cron = "0 0 12 * * ?")@Scheduled(cron = "0 0 18 * * ?")public void performTempFileCleanup() { ... }

@Schedules({ @Scheduled(cron = "0 0 12 * * ?") @Scheduled(cron = "0 0 18 * * ?")})public void performTempFileCleanup() { ... }

Page 21: Spring on Java 8

Parameter Name Discovery● Java 8 defines a rich Parameter reflection type for methods

– application sources to be compiled with -parameters● Spring's StandardReflectionParameterNameDiscoverer

– reading parameter names via Java 8's new Parameter type● Spring's DefaultParameterNameDiscoverer

– now checking Java 8 first (-parameters)– ASM-based reading of debug symbols next (-debug)

Page 22: Spring on Java 8

The State of Java 8, Revisited● Current OpenJDK 8 builds work perfectly well for our purposes

– JSR-310's java.time package is complete– lambdas and method references work great– tracking the latest OpenJDK builds

● IntelliJ IDEA 12 is quite advanced in terms of Java 8 support– works fine with any recent OpenJDK 8 build

● No support for 1.8 bytecode in Gradle's test class detection yet– Gradle is using an unpatched version of ASM 4.0

Page 23: Spring on Java 8

Java 8 Adoption● Spring Framework 4.0 to go GA before OpenJDK 8 GA

– against the OpenJDK 8 Developer Preview release– providing best-effort support for starting Java 8 based apps– immediately production-capable once OpenJDK 8 goes GA

● Consider the use of -target 1.7– implies -source 1.7: no use of Java 8 language features– but rely on Java 8 APIs (JSR-310 etc) and VM benefits– no need for third-party frameworks to be 1.8 compatible yet

Page 24: Spring on Java 8

To Upgrade or Not To Upgrade?● Spring 3.2 does not support the 1.8 bytecode level

– upgrade to Spring 4.0 to enable Java 8 language features● Oracle's JDK support policy is quite aggressive

– JDK 6 already EOL'ed (note: Oracle != IBM)– JDK 7 EOL announcement expected after JDK 8 GA release

● Either way, we recommend an early upgrade to Spring 4.0– Spring Framework 4.0 is still compatible with JDK 6 and 7– Spring Framework 3.2 in maintenance mode already

Page 25: Spring on Java 8

Timeline & Outlook● Spring Framework 4.0 M3 released in August● Spring Framework 4.0 RC1 scheduled for end of September● Spring Framework 4.0 GA in Q4 2013 (late Nov / early Dec)

● Spring Framework 4 is the baseline for Spring Boot● Expect further Spring projects to be Spring 4 based very soon