Your SlideShare is downloading. ×
  • Like
Spring3.0 JaxItalia09
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Spring3.0 JaxItalia09

  • 3,002 views
Published

Spring 3 JaxItalia 2009 slides

Spring 3 JaxItalia 2009 slides

Published in Technology , News & Politics
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,002
On SlideShare
0
From Embeds
0
Number of Embeds
6

Actions

Shares
Downloads
88
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Spring 3.0 What‘s new Massimiliano Dessì, Pronetics S.p.A. 1
  • 2. Speaker Software Engineer and Architect ProNetics Founder Spring Italian User Group Presidente JugSardegna Onlus Committer/Contributor OpenNMS – MongoDB Autore Spring 2.5 Aspect Oriented programming Massimiliano Dessì, Pronetics S.p.a 2
  • 3. Agenda - Allineamento codice con Java 5 - Java based bean metadata - Expression Language - OXM - REST - Declarative Validation - Embedded Database Massimiliano Dessì, Pronetics S.p.a 3
  • 4. Allineamento codice Java 5 Core API allineate con Java 5 recupero di bean senza cast: T getBean(String name, Class<T> requiredType) Map<String, T> getBeansOfType (Class<T> type) Massimiliano Dessì, Pronetics S.p.a 4
  • 5. ApplicationContext <?xml version="1.0" encoding="UTF-8"?> … <bean id="uno" class="it.jax.italia.Uno”> <constructor-arg index="0” value="pippo"/> </bean> <bean id="due" class="it.jax.italia.Due" p:nome="Pluto"/> </beans> Massimiliano Dessì, Pronetics S.p.a 5
  • 6. Recupero bean ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(”beans.xml"); Uno one = ctx.getBean("uno", Uno.class); Map<String,Due> beans = ctx.getBeansOfType(Due.class); Massimiliano Dessì, Pronetics S.p.a 6
  • 7. ApplicationEvent public class MyPublisher implements ApplicationEventPublisherAware { private ApplicationEventPublisher pub; public void setApplicationEventPublisher( ApplicationEventPublisher publisher) { pub = publisher; } public void execute(){ Evento event = new Evento(this, "Hello from mars !"); pub.publishEvent(event); } } Massimiliano Dessì, Pronetics S.p.a 7
  • 8. ApplicationListener Ora possiamo ricevere gli eventi del tipo che ci interessa anzichè dover utilizzare l’instanceof per discriminare public class EventoListener implements ApplicationListener<Evento> { public void onApplicationEvent(Evento event) { .. } } Massimiliano Dessì, Pronetics S.p.a 8
  • 9. Java based bean metadata Ora è possibile configurare l’applicationContext tramite codice Java @Configuration public class Config { private @Value("#{configProperties.url}") String url; @Bean(name="tre") public Tre treService() { return new Tre(url); } @Bean(name="quattro") public Quattro quattroService(){ return new Quattro(treService()); } } Massimiliano Dessì, Pronetics S.p.a 9
  • 10. Java based bean metadata Comunichiamo quale classe contiene la configurazione e l’eventuale properties file. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="it.jax.bean.metadata"/> <util:properties id="configProperties" location="classpath:it/jax/italia/bean/metadata/config.properties"/> </beans> Massimiliano Dessì, Pronetics S.p.a 10
  • 11. SpEL Spring Expression Language Si tratta di un linguaggio molto espressivo che supporta l'interrogazione e la modifica di un grafo di oggetti a runtime, utilizzabile nella configurazione xml, nelle annotazioni nelle firme dei metodi, e questo in tutti I prodotti dello Spring Portfolio Massimiliano Dessì, Pronetics S.p.a 11
  • 12. SpEL #{T(java.util.Calendar).getInstance()} #{T(Integer).toString(675)} #{T(String).CASE_INSENSITIVE_ORDER.compare(“d”,”D”)} #{new java.io.File(‘/tmp/work’).mkdir()} Massimiliano Dessì, Pronetics S.p.a 12
  • 13. SpEL Collections Proiezioni <collection‐name>.![collection‐expression] Selezioni <collection‐name>.?[collection‐expression] Massimiliano Dessì, Pronetics S.p.a 13
  • 14. SpEL Variabili implicite globali systemProperties systemEnvironment Variabili implicite runtime Web servletContext contextProperties – Web application init parameters contextAttributes – attributi Servlet context Request Session servletConfig Massimiliano Dessì, Pronetics S.p.a 14
  • 15. SpEL Variabili implicite runtime Web JSF Request/session/application requestScope sessionScope applicationScopecookie header/headerValues param/paramValues initParam view facesContext Massimiliano Dessì, Pronetics S.p.a 15
  • 16. SpEL Operatori == != < > <= >= instanceof and or ! + ‐*/%^ <expression>? If‐true‐result : if‐false‐result <expression>?: if‐null‐result (Elvis with default) Massimiliano Dessì, Pronetics S.p.a 16
  • 17. SpEL XML Utilizzabile nella configurazione XML dove posso anche riferirli tra loro <bean id="numberGuess" class="org.spring.samples.NumberGuess" p:randomNumber="#{ T(java.lang.Math).random() * 100.0 }"/> <bean id="shapeGuess" class="org.spring.samples.ShapeGuess" p:initialShapeSeed="#{ numberGuess.randomNumber }"/> Massimiliano Dessì, Pronetics S.p.a 17
  • 18. SpEL nel codice private MovieFinder movieFinder; private String defaultLocale; @Value("#{ systemProperties['user.region'] }") public void setDefaultLocale(String defaultLocale){ this.defaultLocale = defaultLocale; } @Autowired public void configure(MovieFinder movieFinder, @Value("#{ systemProperties['user.region'] } String defaultLocale){ this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } Massimiliano Dessì, Pronetics S.p.a 18
  • 19. SpEL Security @PreAuthorize("hasRole('ROLE_SUPERVISOR') or " + "hasRole('ROLE_TELLER') and " + "(#account.balance + #amount >= -#account.overdraft)" ) public void post(Account account, double amount); Massimiliano Dessì, Pronetics S.p.a 19
  • 20. Object XML Mapping In Spring 3.0 è stato creato il package org.springframework.oxm dove troviamo public interface Marshaller { /** * Marshals the object graph with the given root into the provided Result. */ void marshal(Object graph, Result result) throws XmlMappingException, IOException; } Massimiliano Dessì, Pronetics S.p.a 20
  • 21. Object XML Mapping e l’ unmarshall public interface Unmarshaller { /** * Unmarshals the given provided Source into an object graph. */ Object unmarshal(Source source) throws XmlMappingException, IOException; } Massimiliano Dessì, Pronetics S.p.a 21
  • 22. Object XML Mapping Viene fornita l’implementazione con: JAXB 2 Castor XMLBeans JiBX XStream Massimiliano Dessì, Pronetics S.p.a 22
  • 23. Object XML Mapping Per utilizzare JAXB2 si utilizza nella configurazione XML <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:oxm=http://www.springframework.org/schema/oxm xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <oxm:jaxb2-marshaller id="marshaller"> <oxm:class-to-be-bound name="org.samples.airline.schema.Airport"/> <oxm:class-to-be-bound name="org.samples.airline.schema.Flight"/> </oxm:jaxb2-marshaller> <oxm:jaxb2-marshaller id="marshaller" contextPath="org.springframework.ws.samples.airline.schema"/> Massimiliano Dessì, Pronetics S.p.a 23
  • 24. Object XML Mapping Per utilizzare CASTOR si utilizza nella configurazione XML <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:oxm=http://www.springframework.org/schema/oxm xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <bean id="castorMarshaller class="org.springframework.oxm.castor.CastorMarshaller" p:mappingLocation="classpath:mapping.xml" /> Massimiliano Dessì, Pronetics S.p.a 24
  • 25. Object XML Mapping Per utilizzare XMLBeans si utilizza nella configurazione XML <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:oxm=http://www.springframework.org/schema/oxm xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <oxm:xmlbeans-marshaller id="marshaller"/> Massimiliano Dessì, Pronetics S.p.a 25
  • 26. Object XML Mapping Per utilizzare JiBX si utilizza nella configurazione XML <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:oxm=http://www.springframework.org/schema/oxm xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <oxm:jibx-marshaller id="marshaller" target-class="org.springframework.ws.samples.airline.schema.Flight"/> Massimiliano Dessì, Pronetics S.p.a 26
  • 27. Object XML Mapping Per utilizzare XSTREAM si utilizza nella configurazione XML <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:oxm=http://www.springframework.org/schema/oxm xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="aliases"> <props> <prop key="Flight">org.springframework.oxm.xstream.Flight</prop> </props> </property> </bean> Massimiliano Dessì, Pronetics S.p.a 27
  • 28. Date Time support public class AnnotationDrivenDateTimeFormattingShowcase { // by default, printed & parsed using localized short datetime format (no annotation required) e.g. Locale.US=mm/dd/yyyy h:mm:ss a private Date dateField; // printed & parsed using localized short date format e.g. Locale.US=mm/dd/yyyy @DateTimeFormat(dateStyle = Style.SHORT) private Date shortDateField; // printed & parsed using localized short time format e.g Locale.US=h:mm:ss a @DateTimeFormat(timeStyle = Style.SHORT) private Date shortTimeField; // printed & parsed using custom datetime pattern @DateTimeFormat(pattern = "yyyy/mm/dd") private Date dateFieldCustomPattern; Massimiliano Dessì, Pronetics S.p.a 28
  • 29. Date Time support // by default, printed & parsed using localized short datetime format (no annotation required) e.g. Locale.US=mm/dd/yyyy h:mm:ss a private DateTime jodaDateField; // printed & parsed using localized short date format e.g. Locale.US=mm/dd/yyyy @DateTimeFormat(dateStyle = Style.SHORT) private DateTime shortJodaDateField; // printed & parsed using default ISO date time format yyyy-mm-ddThh:mm:ss.SSSZ @ISODateTimeFormat private Date isoDateField; // by default, printed & parsed using localized short datetime format (no annotaiton required) e.g. Locale.US=mm/dd/yyyy h:mm:ss a private Calendar calendar; // printed & parsed using localized short date format e.g. Locale.US=mm/dd/yyyy @DateTimeFormat(dateStyle = Style.SHORT) private Calendar shortCalendar; Massimiliano Dessì, Pronetics S.p.a 29
  • 30. Date Time support // printed & parsed using short datetime format e.g. Locale.US=mm/dd/yyyy h:mm:ss @DateTimeFormat(dateStyle = Style.SHORT, timeStyle=Style.SHORT) private Long millis; /* @Controller method using @DateTimeFormat annotation on method param to specify format of 'dateParam' request parameter*/ @RequestMapping public void handlerMethod(@RequestParam @DateTimeFormat(dateStyle = Style.SHORT) Date dateParam) { } } Massimiliano Dessì, Pronetics S.p.a 30
  • 31. MVC namespace Spring 3.0 RC2 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=http://www.springframework.org/schema/beans xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:mvc=http://www.springframework.org/schema/mvc xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- Turns on support for mapping requests to Spring MVC @Controller methods Also registers default Formatters and Validators for use across all @Controllers --> <mvc:annotated-controllers /> </beans> Massimiliano Dessì, Pronetics S.p.a 31
  • 32. MVC namespace <mvc:annotated-controllers /> indica l’abilitazione dei seguenti bean <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:order=1/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="conversionService" ref="conversionService" /> <property name="validator" ref="validator" /> </bean> </property> </bean> <bean id="conversionService" class="org.springframework.samples.petclinic.util.PetclinicConversionServiceFactory" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> Massimiliano Dessì, Pronetics S.p.a 32
  • 33. REST •  Uri Template support (Client e Controller) •  Rappresentazione HTML, XML, RSS, Atom, PDF, Excel, JSON •  Filtro servlet per il supporto PUT/DELETE •  Costruito su SpringMVC Massimiliano Dessì, Pronetics S.p.a 33
  • 34. REST Possiamo utilizzare delle mappature Rest style: @RequestMapping(value = "/articles/{id}", method = RequestMethod.GET) public ModelAndView getArticle(@PathVariable("id") String id) { return new ModelAndView("articleView", "article", articleFacade.getArticle(id)); } E avere content negotiation nel view resolver Massimiliano Dessì, Pronetics S.p.a 34
  • 35. REST Accedere ai cookie e agli header della request attraverso le annotazioni @RequestMapping("/show") public ModelAndView getInfo(@RequestHeader("region") long regionId, @CookieValue("language") String langId) { ... } Massimiliano Dessì, Pronetics S.p.a 35
  • 36. REST Sopratutto abbiamo un RESTTemplate che come glialtriSpringtemplate semplifica le chiamate REST HTTP RestTemplate DELETE delete(String, String...) GET getForObject(String, Class, String...) HEAD headForHeaders(String, String...) OPTIONS optionsForAllow(String, String...) POST postForLocation(String, Object, String) PUT put(String, Object, String...) Massimiliano Dessì, Pronetics S.p.a 36
  • 37. REST Gli oggetti da e per i metodi del RestTemplate passano attraverso messageconverters per essere convertiti. ByteArrayHttpMessageConverter StringHttpMessageConverter FormHttpMessageConverter SourceHttpMessageConverter MarshallingHttpMessageConverter BufferedImageHttpMessageConverter Il RestTemplate ci permette quindi di fare chiamate da e verso servizi REST in modo semplificato. Massimiliano Dessì, Pronetics S.p.a 37
  • 38. REST Se abbiamo un controller che ha un mappatura di questo tipo: @Controller public class RestController { @RequestMapping(value= "/books/{book}/{pg}”,method = RequestMethod.GET) public String getArticle(@PathVariable("book") String book, @PathVariable("pg") String pg){ … } Massimiliano Dessì, Pronetics S.p.a 38
  • 39. REST Possiamo interrogare il controller precedente attraverso il RestTemplate RestTemplate restTemplate = new RestTemplate(); Map<String,String> vars = new HashMap<String,String>(); vars.put("book", "sandokan"); vars.put("pg", "21"); String uri = "http://example.com/books/{book}/{pg}"; String result = restTemplate.getForObject(uri, String.class, vars); Massimiliano Dessì, Pronetics S.p.a 39
  • 40. Validazione dichiarativa Nelle classi import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class MyBean { @NotNull @Max(64) private String name; @Min(0) private int age; } Massimiliano Dessì, Pronetics S.p.a 40
  • 41. Validazione dichiarativa Configuriamo un JSR 303 validator <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer”> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="validator" ref="validator" /> </bean> </property> </bean> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> Possiamo così usare l’annotazione @Valid nei metodi dei Controller @RequestMapping("/foo", method=RequestMethod.POST) public void processFoo(@Valid Foo foo) { ... } Massimiliano Dessì, Pronetics S.p.a 41
  • 42. Database embedded Supporto per H2, Derby, HSQL Nella configurazione <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:schema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:embedded-database> Massimiliano Dessì, Pronetics S.p.a 42
  • 43. Database embedded Utile soprattutto per l’ utilizzo nei test EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder.type(EmbeddedDatabaseType.H2). script("schema.sql").script("test-data.sql").build(); // do stuff against the db (EmbeddedDatabase extends javax.sql.DataSource) db.shutdown(); Massimiliano Dessì, Pronetics S.p.a 43
  • 44. Database embedded Domande ? Massimiliano Dessì, Pronetics S.p.a 44
  • 45. Grazie per l’attenzione ! Massimiliano Dessì desmax74 at yahoo.it massimiliano.dessi at pronetics.it http://twitter.com/desmax74 http://jroller.com/desmax http://www.linkedin.com/in/desmax74 http://wiki.java.net/bin/view/People/MassimilianoDessi http://www.jugsardegna.org/vqwiki/jsp/Wiki?MassimilianoDessi Spring Framework Italian User Group http://it.groups.yahoo.com/group/SpringFramework-it Massimiliano Dessì, Pronetics S.p.a 45