Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spring vs. Java EE QConSP 2012

31,530 views

Published on

Uma breve disputa entre as plataformas Spring e Java EE, focando bastante em como o CDI melhorou a forma de trabalhar com Java EE.

Published in: Technology, Education

Spring vs. Java EE QConSP 2012

  1. LIGHTWEIGHTWEB APP CHAMPIONSHIP
  2. QCONSP #3Duelo de titãs SPRING vs JAVA EE
  3. QCONSP #3 JUÍZES
  4. QCONSP #3 THE CHALLENGER
  5. JAVA EE PLATFORM • lutador experiente • mudou a tática no Java EE 5 • ganhou confiança: CDI • perdeu peso para ser ágil • quer lutar na nuvem Patrocinado por: Oracle, Red Hat, IBM and otherQCONSP #3 THE CHALLENGER
  6. QCONSP #3 THE CHAMPION
  7. THE SPRING FRAMEWORK • sem derrota desde 2004 • nocauteou o J2EE • luta em qualquer container • golpes fortes com POJOs • sabe explorar bem seu oponente Patrocinado por: Spring SourceQCONSP #3 THE CHAMPION
  8. QCONSP #3 FIGHT CARD
  9. “Spring always depended on Java EE.” Bill BurkeQCONSP #3 FIGHT CARD
  10. Princípio UFC (princípio hollywood) “Don’t fight us, we fight you!”QCONSP #3 ROUND #1
  11. CDIQCONSP #3 ROUND #1
  12. "Spring does, truly, embody many of the best practices of 2004." Gavin KingQCONSP #3 ROUND #1
  13. IoC / DIQCONSP #3 ROUND #1
  14. IoC / DI Spring JavaEE@Controller @Named@Scope(“request”) @RequestScopedpublic class ContatoBean { public class ContatoBean { @Autowired //@Inject @Inject private ContatoDAO dao; private ContatoDAO dao;QCONSP #3 ROUND #1
  15. PersistênciaQCONSP #3 ROUND #2
  16. Persistência Spring JavaEE@Repository @Statelesspublic class ContatoDAO { public class ContatoDAO { @PersistenceContext @PersistenceContext private EntityManager manager; private EntityManager manager; persistence.xml definição datasourceQCONSP #3 ROUND #2
  17. PersistênciaQCONSP #3 ROUND #2
  18. Persistência@Repository Spring @Stateless JavaEEpublic class ContatoDAO { public class ContatoDAO { @Autowired @Resource private JdbcTemplate template; private DataSource ds; public void salva(Contato c){ public void salva(Contato c) { try { template.update( Connection con = ds.getConn..(); "insert ... values (?, ?)", PreparedStatement ps = c.nome(), c.idade()); con.prepareStatement(“insert ..”); } ps.setString(1, c.nome());} ps.setString(1, c.idade()); ps.execute(); ps.close(); }catch(..){} ...QCONSP #3 ROUND #2
  19. PersistênciaQCONSP #3 ROUND #2
  20. Persistência Spring DataQCONSP #3 ROUND #2
  21. Transação e ExceçãoQCONSP #3 ROUND #3
  22. Transação e Exceção Spring JavaEE@Transactional(...) @TransactionAttribute(...)@Repository @Statelesspublic class ContatoDAO { public class ContatoDAO { @PersistenceContext @PersistenceContext private EntityManager manager; private EntityManager manager;<bean id=”xxxTransactionManager” ejb-jar.xml .../>QCONSP #3 ROUND #3
  23. Transação e ExceçãoQCONSP #3 ROUND #3
  24. Transação e Exceção Spring JavaEE@Transaction(rollbackFor= @ApplicationException(rollback=true) DaoException.class) public class DaoExceptionpublic class ContatoController{ extends Exception{}•HandlerExceptionResolver •<error-page>•AOP Proxies •filtros ou interceptadoresQCONSP #3 ROUND #3
  25. QCONSP #3 ROUND #4
  26. Web-Peso leveQCONSP #3 ROUND #4
  27. Web-Peso leve@Controller Spring @Named JavaEE@Transactional @RequestScopedpublic class ContatoController { public class ContatoMB { @Autowired private Contato contato; private ContatoDAO dao; private List<Contato> contatos; @RequestMapping("/adicionar") @Inject public ModelAndView adicionar(Contato c){ private ContatoDAO dao; dao.salva(c); ModelAndView mv = new ModelAndView("ok"); public void salvar(){ mv.addObject("contatos", dao.lista); dao.salva(contato); return mav; zeraForm();} }QCONSP #3 ROUND #4
  28. Web-Peso pesadoQCONSP #3 ROUND #4
  29. Web-Peso pesado Spring JavaEEpublic class EncodingPostProcessor public class UtilMB { implements BeanPostProcessor { public String reset() {public Object postProcessBeforeInitialzation FacesContext context = (Object bean, String name) FacesContext.getCurrentInstance(); throws BeansException Application application ={if(bean instanceof context.getApplication(); AnnotationMethodHandlerAdapter) { ViewHandler viewHandler = application.getViewHandler();HttpMessageConverter<?>[] convs = UIViewRoot viewRoot =((AnnotationMethodHandlerAdapter) viewHandler.createView(context,bean).getMessageConverters(); context.getViewRoot().getViewId()); context.setViewRoot(viewRoot);for (HttpMessageConverter<?> conv : convs) { return "success"; } if(conv instanceof } StringHttpMessageConverter) {((StringHttpMessageConverter) conv).setSupportedMediaTypes(Arrays.asList(new MediaType("text", "Charset.forName("UTF-)}QCONSP #3 ROUND #4
  30. Web Action-based vs. Component-basedQCONSP #3 ROUND #4
  31. Web-Service - SOAPQCONSP #3 ROUND #5
  32. Web-Service - SOAP Spring JavaEE@WebService @WebServicepublic class ContatosWS extends public class ContatosWS{ SpringBeanAutowiringSupport{ @Inject @Autowired ContatoDAO dao; private ContatoDAO dao; public List<Contato> listaDeContatos(){ public List<Contato> listaDeContatos() { return dao.lista(); if(dao==null{ }processInjectionBasedOnCurrentContext(this); } } ...; }}QCONSP #3 ROUND #5
  33. Web-Service - RESTQCONSP #3 ROUND #5
  34. Web-Service - REST@Controller Spring @Path("/") JavaEEpublic class ContatoResource { public class ContatoResource { @Autowired @Inject private ContatoDAO dao; private ContatoDAO dao; @RequestMapping( @GET value = "/contatos/{id}", @Path("/contatos/{id}") produces={"application/json"}, @Produces({"application/json"}) method=RequestMethod.GET) public Contato load(@PathParam("id") @ResponseBody Long id){ public Contato load(@PathVariable("id") return dao.busca(id); Long id) { } return dao.busca(id); } }}QCONSP #3 ROUND #5
  35. MensageriaQCONSP #3 ROUND #6
  36. Mensageria JavaEE - JMS InitialContext ic = new InitialContext(); ConnectionFactory cf = (ConnectionFactory)ic.lookup("Factory"); Connection con = cf.createConnection(..); Session session = con.createSession(false,AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage("oi jms"); Queue queue = (Queue)ic.lookup("jms/queue/loja"); QueueSender sender = session.createSender(queue); sender.send(textMessage); con.close();QCONSP #3 ROUND #6
  37. Mensageria JavaEE - JMS InitialContext ic = new InitialContext(); ConnectionFactory cf = (ConnectionFactory)ic.lookup("Factory"); Connection con = cf.createConnection(..); Session session = con.createSession(false,AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage("oi jms"); Queue queue = (Queue)ic.lookup("jms/queue/loja"); QueueSender sender = session.createSender(queue); sender.send(textMessage); con.close();QCONSP #3 ROUND #6
  38. Mensageria Spring - JMSTemplate @Autowired JmsTemplate template; @Autowired Queue queue; public void enviaMensagem() { this.template.send(queue, new MessageCreator() { public Message createMessage(Session s) throws JMSException { return session.createTextMessage("oi jms"); } }); }QCONSP #3 ROUND #6
  39. Mensageria Spring - JMSTemplate @Autowired JmsTemplate template; @Autowired Queue queue; public void enviaMensagem() { this.template.send(queue, new MessageCreator() { public Message createMessage(Session s) throws JMSException { return session.createTextMessage("oi jms"); } }); }QCONSP #3 ROUND #6
  40. MensageriaQCONSP #3 ROUND #6
  41. Mensageria Spring IntegrationQCONSP #3 ROUND #6
  42. SegurançaQCONSP #3 ROUND #7
  43. Segurança JavaEE - JAAS<security-constraint> @RolesAllowed({"cliente"}) <web-resource-collection> public void salva(Contato contato){ <url-pattern>/adiciona.jsf</url-pattern> //... </web-resource-collection> } <auth-constraint> <role-name>*</role-name> @PermitAll, @DenyAll ... </auth-constraint></security-constraint><login-config> <auth-method>FORM</auth-method>v <form-login-config> <form-login-page>/login.jsf </form-login-page> </form-login-config></login-config><security-role> <role-name>*</role-name></security-role>QCONSP #3 ROUND #7
  44. Segurança JavaEE - JAAS<security-constraint> @RolesAllowed({"cliente"}) <web-resource-collection> public void salva(Contato contato){ <url-pattern>/adiciona.jsf</url-pattern> //... </web-resource-collection> } <auth-constraint> <role-name>*</role-name> @PermitAll, @DenyAll ... </auth-constraint></security-constraint><login-config> <auth-method>FORM</auth-method>v <form-login-config> <form-login-page>/login.jsf </form-login-page> </form-login-config></login-config><security-role> <role-name>*</role-name></security-role>QCONSP #3 ROUND #7
  45. SegurançaQCONSP #3 ROUND #7
  46. Segurança Spring Security<sec:authentication-manager> @Secured({"cliente"}) <sec:authentication-provider public void salva(Contato contato){ user-service-ref="userDAO" /> //... </sec:authentication-manager> }<sec:http auto-config="true"> <sec:intercept-url <sec:authorize access="hasRole(cliente)"> pattern="/contatos.spring" um jsp restrito access="ROLE_USER" /> </sec:authorize> <sec:form-login login-page="/login-form.spring" default-target-url="/contatos.spring" login-processing-url="/login" /> <sec:logout logout-url="/logout" logout-success-url="/login-form.spring"/></sec:http>QCONSP #3 ROUND #7
  47. Infra-SpringQCONSP #3 ROUND #8
  48. Infra-SpringQCONSP #3 ROUND #8
  49. QCONSP #3 ROUND #8
  50. Infra-JavaEEQCONSP #3 ROUND #8
  51. Infra-JavaEEQCONSP #3 ROUND #8
  52. Infra-CloudQCONSP #3 ROUND #8
  53. Extras “We will create new projects where no good solution exists.” SpringSourceQCONSP #3 ROUND #9
  54. ExtrasQCONSP #3 ROUND #9
  55. ExtrasQCONSP #3 ROUND #9
  56. ExtrasQCONSP #3 ROUND #9
  57. Especifição vs ImplementaçãoQCONSP #3 ROUND #10
  58. Especifição vs ImplementaçãoQCONSP #3 ROUND #10
  59. Especifição vs ImplementaçãoQCONSP #3 ROUND #10
  60. Especifição vs Implementação “Standards are for standardizing, and not innovating.” Ed Burns (Líder JSF-Spec )QCONSP #3 ROUND #10
  61. Especifição vs ImplementaçãoQCONSP #3 ROUND #10
  62. Especifição vs Implementação "Stick to the standard when you can, leave the standards when you need." Antonio Goncalves (JCP Expert Member)QCONSP #3 ROUND #10
  63. QCONSP #3 SCORE
  64. QCONSP #3 SCORE
  65. QCONSP #3 SCORE
  66. QCONSP #3 OBRIGADO!
  67. PERGUNTAS?QCONSP #3 OBRIGADO!

×