Slide 1

Slide 1 text

1 1 Spring Framework 4 on Java 8 Juergen Hoeller Spring Framework Lead Pivotal

Slide 2

Slide 2 text

2 2 Spring Framework 3: The State of the Art @Service public class MyBookAdminService implements BookAdminService { @Autowired public MyBookAdminService(AccountRepository ar) { ... } @Transactional public BookUpdate updateBook(Addendum addendum) { ... } }

Slide 3

Slide 3 text

3 3 Composable Annotations @Service @Scope("session") @Primary @Transactional(rollbackFor=Exception.class) @Retention(RetentionPolicy.RUNTIME) public @interface MyService {} @MyService public class MyBookAdminService { ... }

Slide 4

Slide 4 text

4 4 Configuration Classes @Configuration @Profile("standalone") @EnableTransactionManagement public class MyBookAdminConfig { @Bean public BookAdminService myBookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(bookAdminDataSource()); return service; } ... }

Slide 5

Slide 5 text

5 5 Matching an Injection Point to a Factory Method public class MyBookAdminService implements BookAdminService { @Autowired @Qualifier("production") public MyBookAdminService(AccountRepository ar) { ... } } @Bean @Qualifier("production") public AccountRepository myAccountRepository() { return new MyAccountRepositoryImpl(); }

Slide 6

Slide 6 text

6 6 Annotated MVC Controllers @Controller public class MyMvcController { @RequestMapping(value="/books/{id}", method=GET) public Book findBook(@PathVariable long id) { return this.bookAdminService.findBook(id); } @RequestMapping("/books/new") public void newBook(Book book) { this.bookAdminService.storeBook(book); } }

Slide 7

Slide 7 text

7 7 Introducing Spring Framework 4 ● 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+

Slide 8

Slide 8 text

8 8 Spring Framework 4 and Java 8 ● First-class support for Java 8 language and API features – lambda expressions – method references – JSR-310 Date and Time – repeatable annotations – parameter name discovery ● Full runtime compatibility with JDK 8 – for Spring apps built against JDK 6/7 but running against JDK 8

Slide 9

Slide 9 text

9 9 Spring Framework 4 and Groovy import org.mypackage.domain.Person; beans { xmlns util: 'http://www.springframework.org/schema/util' person1(Person) { name = "homer" age = 45 props = [overweight:true, height:"1.8m"] children = ["bart", "lisa"] } util.list(id: 'foo') { value 'one' value 'two' } }

Slide 10

Slide 10 text

10 10 Conditional Bean Definitions ● 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

Slide 11

Slide 11 text

11 11 Composable Annotations with Overridable Attributes @Scope(value="session") @Retention(RetentionPolicy.RUNTIME) public @interface MySessionScoped { ScopedProxyMode proxyMode() default ScopedProxyMode.NO; } @Transactional(rollbackFor=Exception.class) @Retention(RetentionPolicy.RUNTIME) public @interface MyTransactional { boolean readOnly(); }

Slide 12

Slide 12 text

12 12 Generics-based Injection Matching public class MyBookAdminService implements BookAdminService { @Autowired public MyBookAdminService(MyRepository ar) { ... } } @Bean public MyRepository myAccountRepository() { return new MyAccountRepositoryImpl(); }

Slide 13

Slide 13 text

13 13 Messaging and WebSocket ● 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

Slide 14

Slide 14 text

14 14 STOMP on WebSocket @Controller public class MyStompController { @SubscribeEvent("/positions") public List getPortfolios(Principal user) { ... } @MessageMapping("/trade") public void executeTrade(Trade trade, Principal user) { ... } }

Slide 15

Slide 15 text

15 15 Spring Framework 4 and Java EE 7 ● 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 ● JSR-236 Concurrency – Managed(Scheduled)ExecutorService including trigger support

Slide 16

Slide 16 text

16 16 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 in GA form for June 2014 (!) – Spring Tool Suite: Eclipse-based beta support already

Slide 17

Slide 17 text

17 17 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 – several new common interfaces introduced in Java 8

Slide 18

Slide 18 text

18 18 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)

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

20 20 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)); });

Slide 21

Slide 21 text

21 21 Method References with Spring's JdbcTemplate public List 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)); }

Slide 22

Slide 22 text

22 22 JSR-310 Date and Time import 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; ... }

Slide 23

Slide 23 text

23 23 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() { ... }

Slide 24

Slide 24 text

24 24 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)

Slide 25

Slide 25 text

25 25 The State of Java 8, Revisited ● Current OpenJDK 8 builds work perfectly for our purposes – lambdas and method references work great – OpenJDK 8 is beyond its API freeze point already ● IntelliJ IDEA 12 is quite advanced in terms of Java 8 support – works fine with any recent OpenJDK 8 build ● 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

Slide 26

Slide 26 text

26 26 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 ● We strongly recommend an early upgrade to Spring 4 – Spring Framework 4.0 is still compatible with JDK 6 and 7 – Spring Framework 3.2 in maintenance mode already ● Spring Framework 4.0 RC1 released at the end of October ● Spring Framework 4.0 GA to be released in December

Slide 27

Slide 27 text

27 27 Learn More. Stay Connected. New website: spring.io • core framework: projects.spring.io/spring-framework • check out Spring Boot: projects.spring.io/spring-boot Twitter: twitter.com/springcentral YouTube: youtube.com/user/SpringSourceDev © 2013 Spring, by Pivotal gopivotal.com COMING UP Spring eXchange London Nov 14-15