Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Jürgen Höller on Spring 4 on Java 8

Jürgen Höller on Spring 4 on Java 8

More Decks by Enterprise Java User Group Austria

Other Decks in Technology

Transcript

  1. 1 1 Spring Framework 4 on Java 8 Juergen Hoeller

    Spring Framework Lead Pivotal
  2. 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) { ... } }
  3. 4 4 Configuration Classes @Configuration @Profile("standalone") @EnableTransactionManagement public class MyBookAdminConfig

    { @Bean public BookAdminService myBookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(bookAdminDataSource()); return service; } ... }
  4. 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(); }
  5. 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); } }
  6. 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+
  7. 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
  8. 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' } }
  9. 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
  10. 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(); }
  11. 12 12 Generics-based Injection Matching public class MyBookAdminService implements BookAdminService

    { @Autowired public MyBookAdminService(MyRepository<Account> ar) { ... } } @Bean public MyRepository<Account> myAccountRepository() { return new MyAccountRepositoryImpl(); }
  12. 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
  13. 14 14 STOMP on WebSocket @Controller public class MyStompController {

    @SubscribeEvent("/positions") public List<PortfolioPosition> getPortfolios(Principal user) { ... } @MessageMapping("/trade") public void executeTrade(Trade trade, Principal user) { ... } }
  14. 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
  15. 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
  16. 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
  17. 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)
  18. 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)));
  19. 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)); });
  20. 21 21 Method References with Spring's JdbcTemplate public 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)); }
  21. 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; ... }
  22. 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() { ... }
  23. 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)
  24. 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
  25. 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
  26. 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