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

Getting started with Spring in 2014

Getting started with Spring in 2014

Stéphane Nicoll

November 06, 2014
Tweet

More Decks by Stéphane Nicoll

Other Decks in Programming

Transcript

  1. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Getting Started with Spring in 2014 Brian Clozel (@brianclozel) - Stéphane Nicoll (@snicoll)
  2. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ A brief history of Spring ! Started in 2002 ! AOP, IoC and DI ! Templates for JDBC/REST/JMS/… ! Abstractions (e.g. for Cache implementations) 2
  3. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Aspect Oriented Programming 3 public BookLoan loan(User user, Book book) { if(user.isLibrarian()) { // do it } // else... forbidden } @Secured("ROLE_LIBRARIAN") // Spring Security uses AOP to back this public BookLoan loan(Book book) { // do it }
  4. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Dependency Injection 4 // manual, tedious work DataSource ds = ... BookRepository bookRepo = new BookRepository(ds); UserService userService = new UserService(); SearchEngine search = new SearchEngine(bookRepo); LoanService loanService = new LoanService(userService, bookRepo);
  5. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ DI with Spring 1/2 5 package org.example.app; @Configuration // used by the container to bootstrap your app @ComponentScan("org.example.app") // scans packages for Beans public class AppConfig { @Bean public DataSource datasource() { //... return ds; } }
  6. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ DI with Spring 2/2 6 @Component // declare components with annotations public class LoanService { @Autowired public LoanService(UserService userService, BookRepository bookRepo) { //... } }
  7. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Spring Framework offers more! 7 ! Many other features ! Ongoing tradition of supporting standards ! Running in production, everywhere ! Spring 4 minimal requirements: • JDK6 and Servlet 2.5+ • Tomcat 6+, Jetty 7+, JBoss AS 6.1, Glassfish 3.1, Weblogic 10.3, Websphere 7 ! JDK8, Servlet 3.0/3.1 recommended!
  8. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Concrete examples 8
  9. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Application cache ! Required steps: • Configure a cache store • Check if a Book with that id exists in the cache every time the method is invoked • If so return it • If it does not, execute the method and cache the result before returning the value to the user 9 public Book findById(String id) { ... }
  10. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Manual application cache 10 package spring; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import spring.Book; import spring.BookRepository; import org.springframework.util.Assert; public class BookRepositoryImpl implements BookRepository { private Ehcache booksCache; @Override public Book findById(String id) { // Check if item is not in the cache Element cacheHit = booksCache.get(id); if (cacheHit != null) { return (Book) cacheHit.getObjectValue(); } // Fetch the item if it's not in the cache Book result = doFindById(id); if (result != null) { Element element = new Element(id, result); booksCache.put(element); } return result; } protected Book doFindById(String id) { // Actual retrieval } public void setCacheManager(CacheManager cacheManager) { Assert.notNull(cacheManager, "CacheManager must not be null"); this.booksCache = cacheManager.getEhcache("books"); if (this.booksCache == null) { throw new IllegalStateException("No cache named 'books' was found"); } } }
  11. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Manual application cache (cont’d) 11 private Ehcache booksCache; @Override public Book findById(String id) { // Check if item is not in the cache Element cacheHit = booksCache.get(id); if (cacheHit != null) { return (Book) cacheHit.getObjectValue(); } // Fetch the item if it's not in the cache Book result = doFindById(id); if (result != null) { Element element = new Element(id, result); booksCache.put(element); } return result; }
  12. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Manual application cache (cont’d) 12 public void setCacheManager(CacheManager cacheManager) { Assert.notNull(cacheManager, "CacheManager must not be null"); this.booksCache = cacheManager.getEhcache("books"); if (this.booksCache == null) { throw new IllegalStateException("No cache named 'books' was found"); } }
  13. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Configuring manual application cache 13 @Configuration public class ApplicationConfig { @Value("classpath:my-ehcache.xml") private Resource ehCacheConfig; @Bean public CacheManager ehCacheManager() { return EhCacheManagerUtils.buildCacheManager(ehCacheConfig); } @Bean public BookRepository bookRepository() { BookRepositoryImpl bookRepository = new BookRepositoryImpl(); bookRepository.setCacheManager(ehCacheManager()); return bookRepository; } }
  14. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Application cache (the spring way) 14 package spring; import org.springframework.cache.annotation.Cacheable; public class BookRepositoryImpl implements BookRepository { @Override @Cacheable("books") public Book findById(String id) { ... } }
  15. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Configuring application cache (the spring way) 15 @Configuration @EnableCaching public class ApplicationConfig { @Value("classpath:my-ehcache.xml") private Resource ehCacheConfig; @Bean public CacheManager ehCacheManager() { return new EhCacheCacheManager( EhCacheManagerUtils.buildCacheManager(ehCacheConfig)); } @Bean public BookRepository bookRepository() { return new BookRepositoryImpl(); } }
  16. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Application cache (summary) ! No cache store specific access in your code • Separation of concern • Library specific APIs do not leak in your code ! Supported cache stores are updated for you • Ehcache, Hazelcast, JCache, Guava, Redis, JDK HashMap, etc. ! Benefit from new features (JCache support in 4.1) • Super easy once the infrastructure is in place 16
  17. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Getting started guide - Try it out yourself! 17
  18. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Consistent model ! Asynchronous processing - @EnableAsync ! Scheduling - @EnableScheduling ! Executor (TaskExecutor) abstraction 18 @Async public void indexBooks() { // very lengthy operation } @Scheduled(cron = "* * 0/4 * * MON-FRI") public void indexBooks() { ... }
  19. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Reference guide 19
  20. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Auto-generated proxies ! Example: spring data repositories ! Auto-generated implementation • @EnableJpaRepositories • @EnableMongoRepositories 20 @Repository public interface BookRepository extends CrudRepository<Book, Long> { Book findByISBN(ISBN isbn); Book findByAuthorAndTitle(String author, String title); }
  21. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ The Web - Spring MVC 21
  22. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ The Web - Spring MVC 22 ! Controller/Actions based ! Flexible ! Many points of extension ! Community-driven over the years
  23. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Web Controllers / Views 23 @Controller @RequestMapping("/loan") public class BookLoanController { @RequestMapping("/show") public String showLoan(@RequestParam Long loanId, Model model) { BookLoan loan = this.repository.findLoan(loanId); model.add("loan", loan); return "loans/show"; } } http://server:8080/my-app/loan/show?loandId=42
  24. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Web Controllers / REST 24 @RestController("/books") public class BooksController { @Autowired public BooksController(...) { } @RequestMapping("/{id}") public Book findBook(@PathVariable String id) { } } http://server:8080/my-app/books/42
  25. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Web Controllers / Exception Handling 25 @ControllerAdvice(annotations = RestController.class) public class RestControllersAdvice { @ExceptionHandler(BookNotFoundException.class) public ResponseEntity<String> handleNotFoundException( BookNotFoundException ex) { return ResponseEntity.notFound().build(); } }
  26. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Spring Boot 26
  27. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ 27 “Spring Boot lets you pair-program with the Spring team. Josh Long, @starbuxman
  28. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Spring Boot ! Single point of focus ! Get you started very quickly with Spring ! Common non-functional requirements for a "real" application ! Exposes a lot of useful features by default ! Gets out of the way quickly if you want to change defaults ! An opportunity for Spring to be opinionated 28
  29. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Spring Boot - Simple example ! Declare a component when a condition matches ! Spring Boot auto-configuration infrastructure 29 @Configuration @ConditionalOnClass({ RabbitTemplate.class, Channel.class }) @ConditionalOnBean(ConnectionFactory.class) public class AmqpTemplateAutoConfiguration { @Bean @ConditionalOnMissingBean(RabbitTemplate.class) public RabbitTemplate rabbitTemplate(ConnectionFactory cf) { return new RabbitTemplate(cf); } }
  30. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Spring portfolio & Spring platform 30 spring.io/platform
  31. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Your next app? JDK8 + Spring Framework 4 + Spring Boot 31
  32. Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software,

    Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ 32 Learn More. Stay Connected. ! Stay in touch on Twitter ! Watch talks on Youtube ! Ask questions on StackOverflow ! Features and bugs on JIRA Twitter: twitter.com/springcentral YouTube: spring.io/video Questions: spring.io/questions JIRA: jira.spring.io