Das Spring-Framework Eberhard Wolff Regional Director & Principal Consultant SpringSource GmbH Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Über mich... ·! Principal & Regional Director ·! Autor zahlreicher Artikel und des ersten deutschsprachigen Spring-Buchs ·! Speaker auf zahlreichen internationalen Konferenzen ·! Java Champion Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Über SpringSource... ·! Beschäftigen alle Spring-Committer ·! ...und die meisten aus den anderen SpringProjekten ·! Wichtigster Support-Dienstleister im ApacheBereich durch Zukauf von Covalent (Tomcat, HTTPD, ActiveMQ etc.) ·! Training / Consulting / Produkte Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 What we want to build ·! Order / Customer system OrderBusinessProcess Customer Repository Order Repository Item Repository JPA EntityManagerFactory Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 Why this way? ·! Easier testability: Repositories might be replaced with mocks during testing ·! Flexibility: Repositories may use JPA or JDBC for optimizations and hide the details ·! Repositories actually make sense as a design paradigm (see Eric Evans: Domain Driven Design) Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 Dependency Injection Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Dependency Injection ·! Instead of public OrderBusinessProcess() {! EntityManagerFactory em=...;! // How do you create this for Java SE and EE?! orderRepository = new OrderRepository(em);! customerRepository = new CustomerRepository(em);! itemRepository = new ItemRepository(em);! }" ·! Use: public class OrderBusinessProcess {! @Resource(name="customerRepository")! public void setCustomerRepository(ICustomerRepository c) ! { this.customerRepository = c; }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 Why it Dependency Injection (DI) a good thing ·! Because everybody says so! ·! EJB 3 (JSR 220) ·! JSR 250 (Common Annotations) ·! Spring ·! Upcoming standards (Web Beans) Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 But seriously... ·! Easier Testability (exchange implementations with mocks) ·! Independence from the environment (e.g. Java SE vs. Java EE) ­! Good for tests ­! More flexibility ·! Better dependency management ­! Only depend on interfaces ­! I.e. service does not know Repository implementations 9 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. The DI Standard ·! JSR 250: Common Annotations ·! Supported by Spring 2.5 ·! Defines annotations for DI (among other) Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 JSR 250 Annotations ·! @Resource(name=".. ") ­! Inject a certain object ­! JSR 250 says the name is a JNDI name ­! I.e. you need a JNDI system and probably an application server ­! Spring can do without public class OrderBusinessProcess {! @Resource(name="customerRepository")! public void setCustomerRepository(ICustomerRepository c) ! { this.customerRepository = c; }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 More JSR 250 Annotations ·! @PostConstruct ­! Call after construction ­! Dependencies are injected ·! @PreDestroy ­! Guaranteed call before container shut down ­! What finalize() should have been Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 Also supported in Spring ·! @EJB to inject EJB 3 beans ·! @WebServiceRef to inject a JAX WS 2.0 Web Service Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 But... ·! But how do you define DI components? ·! Beyond the scope of JSR 250 ·! Spring uses named normal Java objects ·! "Spring Beans" Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 Spring Beans and @Component ·! The Spring way: Define an annotated class @Component! public class OrderBusinessProcess {! }! ·! Or: @Repository! public class CustomerRepository {! }! ·! @Repository translates persistence exceptions into Spring exceptions ·! I.e. JDBC and JPA can be mixed and the same exceptions are thrown Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 Spring's Plus: Additional Annotations ·! Do you really want to use the name? ­! Adds dependency on the configuration ­! Very often the type is enough ·! @Autowired allows Autowiring-By-Type public class OrderBusinessProcess {! @Autowired! public void setOrderRepository(! IOrderRepository o){ orderRepository=o; }! }! ·! Qualifier allow fine tuning if more than one candidate is found Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 The Spring configuration ·! component-scan for @Component etc. ·! also enables @Resource etc. ! ! ! ! ! 17 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Note: You can have your own Annotation! ·! All the annotations can be exchanged for your own! ·! Just by reconfiguration ·! No dependency on Spring in the code ·! No dependency on JSR 250 in the code Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 But this wires configuration into the code.... ·! Names etc. are in the code ·! No easy reconfiguration ·! XML to the rescue! ! ! ! ! ! ! ! ! ! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 Transactions Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Transactions using pure JPA ·! A multitude of problems public class OrderBusinessProcess {! public Order createOrder(...)! throws OrderException {! EntityManager em = emf.createEntityManager();! em.getTransaction().begin();! }! }! em.getTransaction().commit();! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Problems ·! Service tied to persistence API ·! Violates layering ·! Service cannot be called from a different service and join a transaction ·! What about the Exception? ­! Should a rollback be performed? ­! Is the transaction really ended and the resources freed? Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 Declarative Transaction Propagation ·! @TransactionAttribute ·! Required: Join or start a transaction ·! Originally defined in JSR 220 (EJB 3) ·! I.e. you need an EJB container ·! No tests outside the container possible ·! Spring 2.5 supports this for any environment (SE, EE, JDBC, JMS...) public class OrderBusinessProcess { ! @TransactionAttribute(TransactionAttributeType.REQUIRED) ! public Order createOrder(...) {! }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Spring's Plus: @Transactional ·! Offers the same propagations + NESTED (JDBC) ·! Individual rules for commit / rollback for certain exception types ·! Isolation (JDBC) ·! Read-Only (allows optimizations e.g. for JPA) ·! Timeout Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 How do you actually define such attributes? ·! Your own annotation: ­! @Retry to retry if an Exception was thrown ·! Or other features like centralized tracing Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Spring`s solution: AOP @Aspect! public class AnAspect {! // do something before the method hello! // is executed! @Before("execution(void hello())")! public void doSomething() {! }! // This is how Spring could be implemented:! // do some transaction handling before! // any method with an @Transactional annotation! @Before("execution(@Transactional * *(..))")! public void doTheTransaction() {! }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26 An example... @Aspect! public class RetryAspect {! // Retry a method annotated with @Retry! // if an exception is thrown! @Around("execution(@retry.Retry * *(..))")! public Object retry(ProceedingJoinPoint joinPoint)! throws Throwable {! try {! // proceed with the method call! return joinPoint.proceed()! } catch (Exception e) {! return joinPoint.proceed();! }! }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27 Another example... @Aspect! public class RetryAspect {! // Retry a method in a class of the service package or! // subpackages if an exception is thrown! @Around("execution(* service..*.*(..))")! public Object retry(ProceedingJoinPoint joinPoint)! throws Throwable {! try {! // proceed with the method call! return joinPoint.proceed()! } catch (Exception e) {! return joinPoint.proceed();! }! }! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 XML: Transactions without Annotations all over the code ! ! ! ! ! ! ! ! ! ! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 AOP ·! Allows centralized implementation of things otherwise scattered over the code ­! cross cutting concerns ­! Note: It is not needed to annotate the classes ­! You can also use package names etc. ­! I.e. the original code need not be changed ­! ...or you can use Annotations Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30 Implementations: Spring AOP vs. AspectJ ·! @Aspect examples can be used with Spring AOP or AspectJ ·! Spring AOP: Dynamic Proxies or generated subclasses ­! Same as in most application server for @TransactionAttribute etc. ­! Somewhat slow ·! AspectJ: Byte Code manipulation at compile or load time ­! As fast as it gets Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31 A note on Security ·! AOP allows Security without changes to the original code ·! Not just role based, also ACLs etc. ·! But also for specific instance based rules ·! I.e. user may only see his customers ·! Implemented in Spring Security ·! Supports standards like JAAS etc. Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32 JPA Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. What is JPA? ·! An Object / Relational Mapper (O/R Mapper) ·! I.e. translates classes into tables ·! Inheritance is handled ·! Object navigation is handled with lazy loading of dependent object ·! Changes to objects are automatically propagated to the database Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34 JPA ·! How are the classes mapped to tables? ­! Classes must be annotated ­! ...or have an XML configuration ·! How do you access objects in the database? ­! Use the EntityManager Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35 Example public class CustomerRepository {! private EntityManager em;! @PersistenceContext! public void setEntityManager(EntityManager em) {! this.em = em; }! public List getByName(String name) {! return em.createQuery(! "SELECT k FROM Customer k WHERE k.name=?1").! setParameter(1,name).getResultList();! }! public Customer getByID(int id) {! return em.find(Customer.class, id);! }! public Customer save(Customer customer) {! em.persist(customer);! return customer;! }! 36 }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Seems easy enough... ·! Use the EntityManager ·! Have it injected with @PersistenceContext (JSR 220) ·! All operations in the same transaction must use the same EntityManager ·! Automatically dealt with ·! ...if you use Spring Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37 Spring's Plus ·! @PersistenceContext works in Java SE (e.g. for testing) ·! ...and in Java EE artifacts (EJBs, Servlets etc.) ·! Advantage e.g. for test using the IDE Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38 Easier migration by enhancing the standard ·! An advantage of a standard is easy migration ·! How hard is it to migrate from one JPA vendor to another? ·! Spring unifies specific options ­! for the configuration of the database ­! whether a schema should be generated ­! whether the SQL should be shown ­! Makes migration easier Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39 JPA: Weaving ·! JPA implementation must be able to modify classes ·! Standardized JPA: Either using a Java agent (Java SE) or the Java EE server ·! Might even need to deploy a persistence provider ·! What about a web server? Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40 JPA: Spring ·! Spring offers the JPA implementation the same services like a Java EE server ·! ...but on any environment (SE, EE ...) ·! General Abstraction ·! EJB and Web Container supported ·! Also allows AspectJ Load Time Weaving Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41 Anderer PersistenzTechnologien ohne Spring Connection con = null; ResultSet rs; Größtenteils schwer diagnostizierbar! try { con = ...; Statement stmt = con.createStatement(); List kunden = new ArrayList(); rs = stmt.executeQuery("SELECT * FROM KUNDE"); while (rs.next()) { kunden.add(new Kunde(rs.getInt(1),...)); } rs.close() fehlt (?) stmt.close(); }catch(SQLException e) { System.out.println("SQL-Exception:"+e); }finally { con.close(); NullPointerException? } Wird nicht immer ausgeführt Fehlerbehandlung? SQLException? Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42 Dasselbe mit Spring private static class KundeResultSetRowMapper implements ParameterizedRowMapper { public Kunde mapRow(ResultSet rs, int rowNum) { return new Kunde(rs.getString(1)...); } } getSimpleJdbcTemplate().query( "SELECT * FROM KUNDE WHERE ID=?", new KundeResultSetRowMapper(), id); Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43 Anderes Beispiel: JMS QueueConnectionFactory qcf = ...; QueueConnection qc = null; Queue queue = null; try { qc = qcf.createQueueConnection(); QueueSession qsession = qc.createQueueSession( false,Session.AUTO_ACKNOWLEDGE); QueueSender qsender= qsession.createSender(queue); TextMessage msg = qsession.createTextMessage(); msg.setText("Text"); qsender.send(msg); } catch (JMSException jmsex) { jmsex.printStackTrace(); } finally { qc.close(); } 44 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. JMS mit Spring jmsTemplate.convertAndSend("Eine Text Message"); Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45 Was sonst noch passiert... Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Covalent ·! Im Januar 2008 gekauft ·! >10 Jahre kommerzieller Support für Projekte der Apache Software Foundation (ASF) ·! Kunden: >50% der Fortune 500 und 20% der Global 2000 ·! Beschäftigt ASF Committers für alle unterstützten Technologien mit führenden Rollen bei: ­! Apache Tomcat ·! Java Magazin: 60% nutzen ihn für alle Web Projekte, weiter 35% gelegentlich ·! der am weitesten verbreiteste Web-Server (62%) ­! Apache HTTP Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 47 Das ist noch nicht alles... Spring 2.5 SpringSource Advanced Pack for Oracle SpringSource Support SpringSource Tool Suite Spring Security 2.0 (Acegi) Spring Batch 1.0 SpringSource Application Management Suite Spring Integration Spring Web Services 1.5 Spring OSGi 1.0 Spring WebFlow 2.0 Spring Enterprise Spring .NET 1.1 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 48 Spring Enterprise Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. SpringSource Support ·! Unterstützung bei Produktions- und EntwicklungsProblemen ·! Garantierte Antwortzeiten anhand objektiver Prioritäten ·! Zugriff per Web, EMail und Telefon ·! Wir beschäftigen alle Committer: ­! Möglicher Rückgriff auf den ursprünglichen Entwickler ­! Bug Fixes wandern in die Code-Basis ·! Unterstützt auch Tomcat, Apache ... Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 50 SpringSource Application Management Suite ·! Management von Spring-Anwendungen ·! Relevante Daten automatisch verfügbar ­! ­! ­! ­! Transaktions-Raten Fehler/Exceptions View-Rendering Methoden-Ausführungszeiten ·! Werden über JMX mit Integrationsmöglichkeiten in viele Tools exportiert ·! ...oder über Hyperic in einer Web-ManagementOberfläche verfügbar ·! Live Demo Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 51 SpringSource Advanced Pack for Oracle ·! Oracle Real Application Cluster: Ausfallsichere Datenbank ·! Aber: Bei einem Ausfall geht die aktuelle Transaktion verloren ·! ...nicht mehr mit dem Advanced Pack for Oracle und Spring ·! Außerdem Unterstützung für Oracle DataSources, Oracle Data Types ... Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 52 SpringSource Tool Suite ·! Basiert auf Eclipse ·! Integration der üblichen Enterprise Java Plug Ins ·! Basiert auf Mylyn (task-basierte IDE) ·! Eigene Features: ­! Task-basierte Tutorial für verschiedene Spring-Technologien ­! Spring Best Practises ­! Runtime Error Analysis ·! Live Demo! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 53 To sum up... ·! Dependency Injection using JSR 220, JSR 250 and Spring's or your own Annotations ·! XML for total technology independence in the code ·! @TransactionAttribute (JSR 220) can be used in any environment using Spring ·! @Transactional and XML based configuration offer more features ·! AOP allows you do add more features like that ·! JPA is fully supported in any environment ·! Significant simplification of diverse Java APIs ·! A growing eco system and professional support Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 54 Spring 3.0 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Plan für Spring 3.0 ·! Java 5+ als Basis ­! kompatibel zu J2EE 1.4 und Java EE 5 ·! Spring Expression Language ·! Erweiterungen bei Spring MVC ­! REST ­! AJAX ­! Modell-Validierungen ·! Portlet 2.0 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 56 Expression Language in Bean Definitionen ! ! ! ! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 57 Spring MVC 2.5 @Controller! public class RewardsController {! @RequestMapping("/rewards/show")! public Reward show(@RequestParam("id") Long id) {...}! }! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 58 REST in MVC - @PathParam @RequestMapping(method = RequestMethod.GET)! public Reward show(@PathParam Long id) {! return this.rewardsAdminService.findReward(id);! } http://rewarddining.com/show/12345 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 59 Alternative: REST mit Interfaces @Controller! public class AccountsController! implements RestController {! GET http://rewarddining.com/accounts public List index() {}! public void create(Account account) {}! PUT http://rewarddining.com/accounts public Account show(Long id) {}! GET http://rewarddining.com/accounts/1 public void delete(Long id) {}! DELETE http://rewarddining.com/accounts/1 public http://rewarddining.com/accounts/1 POST void update(Account account) {}! } Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 60 Verschiedene Repräsentationen ·! JSON GET http://rewarddining.com/accounts/1 accepts application/json GET http://rewarddining.com/accounts/1.json ·! XML ·! ATOM GET http://rewarddining.com/accounts/1 accepts application/xml GET http://rewarddining.com/accounts/1.xml GET http://rewarddining.com/accounts/1 accepts application /atom+xml GET http://rewarddining.com/accounts/1.atom Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 61 Modell-Validerungen public class Reward {! @NotNull! @ShortDate! private Date transactionDate;! } In der View:! ! ·! Wird auf Client und Server überprüft ·! Automatische Updates der Validierungs-Fehler mit AJAX ·! Im Blick: JSR-303 und Hibernate Validator...! Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 62 Weitere Web-Features ·! Nicht definitiv ·! Conversation management ­! Mehrere Tabs/Fenster im selben Browser ­! Lebensdauer zwischen Request und Session ·! Stateful Controller ­! Statt zustandslosen Controller + Session -Management ­! Insbesondere mit Conversations spannend Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 63 Pruning & Deprecation in 3.0 ·! Pruning (=Entfernen) ­! Commons Attributes Unterstützung ­! Unterstützung für traditionelle TopLink API ­! Stattdessen: JPA (EclipseLink) ·! Deprecation ­! Traditionelle MVC Controller Klassen ·! Ersatz: Annotationen für MVC ­! Traditionelle JUnit 3.8 Testklassen ·! Ersatz: Annotationen mit JUnit4-Support Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 64 Spring 3.0 Zusammenfassung ·! Spring 3.0 ermöglicht REST und EL ·! Spring 3.0 bietet Erweiterungen bei den Annotationen für Web Controllers ­! RESTful URIs ­! Model-Validierungne mit Annotationen ·! Spring 3.0 ist rückwärtskompatibel zu Spring 2.5 auf Java 5+ ­! Einfache Migration Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 65 Spring 3.0 Roadmap ·! Spring 3.0 M1: September 2008 ·! Spring 3.0 RC1: Dezember 2008 ·! Spring 3.0 final: Januar 2009? ­! Hängt vom Feedback ab Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 66 In eigener Sache: Trainings ·! ·! ·! ·! ·! 16.-19.09.08 21.-24.10.08 18.-21.11.08 25.-28.11.08 02.-05.12.08 Core Core Core Core Core Spring Spring Spring Spring Spring Hamburg Zürich Stuttgart Wien München ·! 28.-30.10.08 Rich Web Applications München ·! 04.-06.11.2008 Spring.Net München ·! Siehe http://springsource.com/de Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 67 We deliver the world`s leading Enterprise JavaTM Platform Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 68