SlideShare a Scribd company logo
 
 
Conhecer as facilidades de e-mails do Spring Saber agendar tarefas com JDK Task Saber interceptar métodos com AOP Saber montar um contexto de teste com JUnit Saber expor serviço via RMI
Depedências: mail.jar activation.jar MailSender Hierarquia de exceptions:
Funcionalidades especializadas para o envio de e-mail com suporte MIME(MimeMessagePreparator) < bean  id = &quot;mailSender&quot; class = &quot;org.springframework.mail.javamail.JavaMailSenderImpl&quot; > < property  name = &quot;host&quot;  value = &quot;host.url.com.br&quot;  /> < property  name = &quot;password&quot;  value = &quot;senha&quot;  /> < property  name = &quot;username&quot;  value = &quot;username@host.com.br&quot;  /> </ bean >   < bean  id = &quot;simpleMailMessage&quot; class = &quot;org.springframework.mail.SimpleMailMessage&quot; > < constructor-arg  index = &quot;0&quot;  ref = &quot;templateMessage&quot;  /> < property  name = &quot;to&quot;  value = &quot;to@server.com&quot;  /> < property  name = &quot;text&quot;  value = &quot; 123 Testando... &quot;  /> </ bean >
package  com.targettrust.spring.email; import  org.springframework.context.ApplicationContext; import  org.springframework.context.support.ClassPathXmlApplicationContext; import  org.springframework.mail.MailException; import  org.springframework.mail.MailSender; import  org.springframework.mail.SimpleMailMessage; public   class  TesteEnviaEmail { public   static   void  main(String[] args) { ApplicationContext ac =  new   ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; );  SimpleMailMessage msg = (SimpleMailMessage)ac.getBean( &quot;simpleMailMessage&quot; ); MailSender ms = (MailSender)ac.getBean( &quot;mailSender&quot; ); try { ms.send(msg); } catch (MailException ex) {  ex.printStackTrace();  } } }
package  com.targettrust.spring.email; import  java.io.File; import  javax.mail.internet.MimeMessage; import  org.springframework.context.ApplicationContext; import  org.springframework.context.support.ClassPathXmlApplicationContext; import  org.springframework.core.io.FileSystemResource; import  org.springframework.mail.javamail.JavaMailSender; import  org.springframework.mail.javamail.MimeMessageHelper; public   class  TesteMimeMessageHelperAtt { public   static   void  main( String [] args) { ApplicationContext ac =  new  ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; ); JavaMailSender ms = (JavaMailSender)ac.getBean( &quot;mailSender&quot; ); try { MimeMessage message = ms.createMimeMessage(); MimeMessageHelper helper =  new  MimeMessageHelper(message, true ); helper.setFrom( &quot;from@server.com.br&quot; ); helper.setTo( &quot;to@server.com&quot; ); helper.setText( &quot;Email MimeMessageHelper&quot; ); FileSystemResource file =  new  FileSystemResource( new   File( &quot;.&quot; ).getCanonicalPath() +  &quot;/build.xml&quot; ); helper.addAttachment( &quot;build.xml&quot; , file); ms.send(message); } catch (Exception e){   e.printStackTrace(); } } }
package  com.targettrust.spring.email; import  java.io.File; import  javax.mail.internet.MimeMessage; import  org.springframework.context.ApplicationContext; import  org.springframework.context.support.ClassPathXmlApplicationContext; import  org.springframework.core.io.FileSystemResource; import  org.springframework.mail.javamail.JavaMailSender; import  org.springframework.mail.javamail.MimeMessageHelper; public   class  TesteMimeMessageHelperAttImg { public   static   void  main(String[] args) { ApplicationContext ac =  new  ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; ); JavaMailSender ms = (JavaMailSender)ac.getBean( &quot;mailSender&quot; ); try { MimeMessage message = ms.createMimeMessage(); MimeMessageHelper helper =  new  MimeMessageHelper(message, true ); helper.setFrom( &quot;form@server.com.br&quot; ); helper.setTo( &quot;dest@server.com&quot; ); helper.setText( &quot;<html><body><img src='cid:img1'><br>Email MimeMessageHelper com suporte a imagems em linha!</body></html>&quot; , true ); FileSystemResource file =  new  FileSystemResource( new   File( &quot;.&quot; ).getCanonicalPath() +  &quot;/imagem.jpg&quot; ); helper.addInline( &quot;img1&quot; , file); ms.send(message); } catch (Exception e){ e.printStackTrace(); } } }
Agendamento de Tarefas Utiliza beans Execução de tempos em tempos Ecolha: menos XML VS menos Acoplamento Timer JDK
package  com.targettrust.spring.jdktask; import  java.util.Date; import  java.util.TimerTask; public   class  HoraCertaService  extends  TimerTask{ @Override @SuppressWarnings ( &quot;deprecation&quot; ) public   void  run() { System. out .println( new  Date().getHours()  +  &quot;:&quot;  +    new  Date().getMinutes() +  &quot;:&quot;  +   new  Date().getSeconds()   ); } }
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean  id = &quot;horaCertaService&quot; class = &quot;com.targettrust.spring.jdktask.HoraCertaService&quot;  /> < bean  id = &quot;scheduledTask&quot; class = &quot;org.springframework.scheduling.timer.ScheduledTimerTask&quot; lazy-init = &quot;false&quot; > <!-- Espera 0 ms antes de iniciar --> < property  name = &quot;delay&quot;  value = &quot;0&quot;  /> <!-- roda de 1 em 1 segundo --> < property  name = &quot;period&quot;  value = &quot;1000&quot;  /> <!-- Ira executar a TimerTask horaCertaService --> < property  name = &quot;timerTask&quot;  ref = &quot;horaCertaService&quot;  /> </ bean > </ beans >
< bean  id = &quot;timerFactory“        class = &quot;org.springframework.scheduling.timer.TimerFactoryBean” > < property  name = &quot;scheduledTimerTasks&quot; >   < list >   < ref  bean = &quot;scheduledTask&quot;  />   </ list > </ property > </ bean >
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean  id = &quot;horaCertaServiceNaoAcoplada&quot; class = &quot;com.targettrust.spring.jdktask.HoraCertaServiceNaoAcoplada“ /> < bean  id = &quot;scheduledTask“  lazy-init = &quot;false&quot; class = &quot;org.springframework.scheduling.timer.ScheduledTimerTask” > <!-- Espera 0 ms antes de iniciar --> < property  name = &quot;delay&quot;  value = &quot;0&quot;  /> <!-- roda de 1 em 1 segundo --> < property  name = &quot;period&quot;  value = &quot;1000&quot;  /> <!-- Ira executar a TimerTask horaCertaService --> < property  name = &quot;timerTask&quot;  ref = &quot;executor&quot;  /> </ bean > < bean  id = &quot;executor&quot;  class = &quot;org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean“ > < property  name = &quot;targetObject&quot;  ref = &quot;horaCertaServiceNaoAcoplada&quot;  /> < property  name = &quot;targetMethod&quot;  value = &quot;showTime&quot;  />   </ bean > < bean  id = &quot;timerFactory&quot;  class = &quot;org.springframework.scheduling.timer.TimerFactoryBean“ > < property  name = &quot;scheduledTimerTasks&quot; > < list >   < ref  bean = &quot;scheduledTask&quot;  /> </ list > </ property > </ bean > </ beans >
Utiliza AOP com AspectJ Abstrações sobre o AspectJ Weaving em runtime Dependências: aspectjweaver.jar aspectjrt.jar
 
 
package  com.targettrust.spring.aop; public   interface  Service { public   void  fazAlgo(); }   package  com.targettrust.spring.aop; import  org.apache.commons.logging.Log; import  org.apache.commons.logging.LogFactory; public   class  ServiceA  implements  Service{ private   static   final  Log  log  = LogFactory. getLog (ServiceA. class ); @Override public   void  fazAlgo() { log .info( &quot;Fiz algo do tipo A&quot; ); } }   package  com.targettrust.spring.aop; import  org.apache.commons.logging.Log; import  org.apache.commons.logging.LogFactory; public   class  ServiceB  implements  Service{ private   static   final  Log  log  = LogFactory. getLog (ServiceB. class ); @Override public   void  fazAlgo() { log .info( &quot;Fiz algo do tipo B&quot; ); } }
package  com.targettrust.spring.aop; import  org.apache.commons.logging.Log; import  org.apache.commons.logging.LogFactory; public   class  ServiceC  implements  Service{ private   static   final  Log  log  = LogFactory. getLog (ServiceC. class ); @Override public   void  fazAlgo() { log .info( &quot;Fiz algo do tipo C&quot; ); } }
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:aop = &quot;http://www.springframework.org/schema/aop&quot; xmlns:tx = &quot;http://www.springframework.org/schema/tx&quot; xsi:schemaLocation = &quot; http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot; > < aop:aspectj-autoproxy /> < bean  id = &quot;aspecto“  lazy-init = &quot;false&quot; class = &quot;com.targettrust.spring.aop.Aspecto“ /> < bean  id = &quot;sa“  class = &quot;com.targettrust.spring.aop.ServiceA“  /> < bean  id = &quot;sb“  class = &quot;com.targettrust.spring.aop.ServiceB“  /> < bean  id = &quot;sc“  class = &quot;com.targettrust.spring.aop.ServiceC“  /> < bean  id = &quot;services“  class = &quot;java.util.ArrayList“  > < constructor-arg  index = &quot;0&quot; > < list > < ref  bean = &quot;sa&quot;  /> < ref  bean = &quot;sb&quot;  /> < ref  bean = &quot;sc&quot;  /> </ list > </ constructor-arg > </ bean > </ beans >
package  com.targettrust.spring.aop; import  org.apache.commons.logging.Log; import  org.apache.commons.logging.LogFactory; import  org.aspectj.lang.ProceedingJoinPoint; import  org.aspectj.lang.annotation.After; import  org.aspectj.lang.annotation.Around; import  org.aspectj.lang.annotation.Aspect; import  org.aspectj.lang.annotation.Before; @Aspect public   class  Aspecto { private   static   final  Log  log  = LogFactory. getLog (Aspecto. class ); @Before ( &quot;execution(* com.targettrust.spring.aop.Service.*(..))&quot; ) public   void  execucaoDeFazAlgoAntes() { log .info( &quot;To sabendo antes da execu ç ão de Service&quot; ); } @After ( &quot;execution(* com.targettrust.spring.aop.Service.*(..))&quot; ) public   void  execucaoDeFazAlgoDepois() { log .info( &quot;To sabendo depois da execu ç ão de Serice&quot; ); } @Around ( &quot;execution(* com.targettrust.spring.aop.ServiceB.faz*(..)))&quot; )  public  Object doBasicProfiling(ProceedingJoinPoint pjp)  throws  Throwable {   Object retVal = pjp.proceed();   log .info( &quot;To sabendo around SericeB&quot; );   return  retVal; } }
Integração com Junit e TestNG Auto-injeção de propriedades  Rollback automático após o teste Prove testes integrados sem servidor de aplicação, mas usando transação e banco de dados. Cache
AbstractDependencyInjectionSpringContextTests AbstractAnnotationAwareTransactionalTests: @DirtiesContext : Annotation que faz o mesmo que o método  setDirty isso fará que o contexto seja recarregado nesse método. @ExpectedException:  Annotation que sinaliza que o método deve  retornar um exception específica, se ele não retornar o teste irá falhar. @NotTransactionl : Indica que esse método roda fora do contexto de transações do Spring. @Repeat : Essa annotation recebe um número, por exemplo 5.  O Spring irá repitir esse teste 5 vezes. AbstractTransactionalDataSourceSpringContextTests
package  com.targettrust.spring.testing; import  java.util.Date; import  junit.framework.Assert; import  org.springframework.test.AbstractDependencyInjectionSpringContextTests; public   class  TestDataService  extends  AbstractDependencyInjectionSpringContextTests { private  DataService  dataService ; public   void  setDataService(DataService dataService) { this . dataService  = dataService; } @Override protected  String[] getConfigLocations() {   return   new  String[]{ &quot;classpath:com/targettrust/spring/testing/Spring-beans.xml&quot; }; } @SuppressWarnings ( &quot;deprecation&quot; ) public   void  testDataDoDataService(){ Date d =  dataService .getSysDate(); Date l =  new  Date(); Assert. assertEquals (d.getDay(),l.getDay()); Assert. assertEquals (d.getMonth(),l.getMonth()); Assert. assertEquals (d.getYear(),l.getYear()); } }
Exposição de beans Pode ser: RMI, JAX-RPC, JMS, Hessian, Burlap, Http Invoker e até mesmo EJB. Para RMI: Serializable Porta na máquina Abstração sob o RMI
package  com.targettrust.spring.remoting; import  java.util.Date; public   interface  HoraService { public  Date getDate(); }   package  com.targettrust.spring.remoting; import  java.util.Calendar; import  java.util.Date; public   class  HoraServiceImpl  implements  HoraService{ public  Date getDate() { return  Calendar. getInstance ().getTime(); } }   <? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean  id = &quot;horaService&quot;  class = &quot;com.targettrust.spring.remoting.HoraServiceImpl”  />     < bean  class = &quot;org.springframework.remoting.rmi.RmiServiceExporter” > < property  name = &quot;serviceName&quot;  value = &quot;Target-HoraService&quot; /> < property  name = &quot;service&quot;  ref = &quot;horaService&quot; /> < property  name = &quot;serviceInterface“  value = &quot;com.targettrust.spring.remoting.HoraService&quot; /> < property  name = &quot;registryPort&quot;    value = &quot;1199&quot; /> </ bean > </ beans >
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = “ http://www.springframework.org/schema/beans ” xmlns:xsi = “ http://www.w3.org/2001/XMLSchema-instance ” xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean  id = &quot;horaService” class = &quot;org.springframework.remoting.rmi.RmiProxyFactoryBean&quot; > < property  name = &quot;serviceUrl&quot;    value = &quot;rmi://localhost:1199/Target-HoraService&quot; /> < property  name = &quot;serviceInterface&quot;  value = &quot;com.targettrust.spring.remoting.HoraService&quot; /> </ bean > </ beans >
Crie um Aspecto para logar todas as chamadas aos dados de um sistema Crie um agendamento com JDK Task que de 5 em 5 segundos manda um e-mail para uma pessoa informando se ouve alguma mudança no sistema. Crie um serviço de calculadora e exporte ele via RMI, faça um porgrama cliente com o suporte de Junit do Spring e suas classes de teste.

More Related Content

PPT
Learn ASP.NET AJAX in 5 Minutes
PPT
GTLAB Overview
PDF
The MetaCPAN VM Part II (Using the VM)
ODP
Mangling
PPT
Assurer - a pluggable server testing/monitoring framework
PPT
How Danga::Socket handles asynchronous processing and how to write asynchrono...
KEY
LvivPy - Flask in details
PDF
Symfony2 Components - The Event Dispatcher
Learn ASP.NET AJAX in 5 Minutes
GTLAB Overview
The MetaCPAN VM Part II (Using the VM)
Mangling
Assurer - a pluggable server testing/monitoring framework
How Danga::Socket handles asynchronous processing and how to write asynchrono...
LvivPy - Flask in details
Symfony2 Components - The Event Dispatcher

What's hot (20)

PDF
The MetaCPAN VM for Dummies Part One (Installation)
PDF
Flask Introduction - Python Meetup
PPT
Perlbal Tutorial
DOCX
My java file
PDF
Spring hibernate jsf_primefaces_intergration
PPT
Testing Javascript with Jasmine
PDF
Containers & Dependency in Ember.js
PDF
Flask patterns
PDF
Practical Celery
PPTX
Flask – Python
PDF
Django Celery - A distributed task queue
ODP
Europython 2011 - Playing tasks with Django & Celery
PPTX
AngularJS Unit Testing
PDF
Droidcon ES '16 - How to fail going offline
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PDF
Java Libraries You Can’t Afford to Miss
PDF
Rest api with Python
PPT
Servlet11
PDF
Jasmine BDD for Javascript
PDF
The JavaFX Ecosystem
The MetaCPAN VM for Dummies Part One (Installation)
Flask Introduction - Python Meetup
Perlbal Tutorial
My java file
Spring hibernate jsf_primefaces_intergration
Testing Javascript with Jasmine
Containers & Dependency in Ember.js
Flask patterns
Practical Celery
Flask – Python
Django Celery - A distributed task queue
Europython 2011 - Playing tasks with Django & Celery
AngularJS Unit Testing
Droidcon ES '16 - How to fail going offline
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Java Libraries You Can’t Afford to Miss
Rest api with Python
Servlet11
Jasmine BDD for Javascript
The JavaFX Ecosystem
Ad

Viewers also liked (19)

PDF
Apache flink
PDF
Lean the principles
PDF
Agile tem que morrer? Já morreu? Hacker way? BS ou mais do mesmo?
PDF
ML and R
PDF
Apache mesos
PDF
Agile culture & Mindsets
PDF
EXTRA: Workshop SOA, Microservices e Devops - Discoverability + Ui Arch
PDF
PDF
PDF
Contracts and models
PDF
PDF
PPT
Spring Capitulo 01
PDF
Twitter Bootstrap
PDF
Apache Kafka
PDF
Cassandra
PDF
Cloud Native, Microservices and SRE/Chaos Engineering: The new Rules of The G...
PDF
Cloud-Native DevOps Engineering
PDF
Microservices reativos usando a stack do Netflix na AWS
Apache flink
Lean the principles
Agile tem que morrer? Já morreu? Hacker way? BS ou mais do mesmo?
ML and R
Apache mesos
Agile culture & Mindsets
EXTRA: Workshop SOA, Microservices e Devops - Discoverability + Ui Arch
Contracts and models
Spring Capitulo 01
Twitter Bootstrap
Apache Kafka
Cassandra
Cloud Native, Microservices and SRE/Chaos Engineering: The new Rules of The G...
Cloud-Native DevOps Engineering
Microservices reativos usando a stack do Netflix na AWS
Ad

Similar to Spring Capitulo 05 (20)

ODP
ActiveWeb: Chicago Java User Group Presentation
ODP
Os Leonard
PPT
ODP
Interoperable Web Services with JAX-WS
PPT
Jsp And Jdbc
ODP
Testing RESTful Webservices using the REST-assured framework
PPT
Boston Computing Review - Java Server Pages
PPT
I Feel Pretty
PPT
Struts2
PPT
Introducing Struts 2
PPT
AJAX Workshop Notes
ODP
Java Boilerplate Busters
ODP
Apache Aries Blog Sample
PPT
Apache Camel - WJax 2008
PDF
Riding Apache Camel
PPT
DWR, Hibernate and Dojo.E - A Tutorial
PPTX
สปริงเฟรมเวิร์ค4.1
PPT
Even Faster Web Sites at jQuery Conference '09
PDF
What's Coming in Spring 3.0
PPT
JMS Introduction
ActiveWeb: Chicago Java User Group Presentation
Os Leonard
Interoperable Web Services with JAX-WS
Jsp And Jdbc
Testing RESTful Webservices using the REST-assured framework
Boston Computing Review - Java Server Pages
I Feel Pretty
Struts2
Introducing Struts 2
AJAX Workshop Notes
Java Boilerplate Busters
Apache Aries Blog Sample
Apache Camel - WJax 2008
Riding Apache Camel
DWR, Hibernate and Dojo.E - A Tutorial
สปริงเฟรมเวิร์ค4.1
Even Faster Web Sites at jQuery Conference '09
What's Coming in Spring 3.0
JMS Introduction

More from Diego Pacheco (20)

PDF
Naming Things Book : Simple Book Review!
PDF
Continuous Discovery Habits Book Review.pdf
PDF
Thoughts about Shape Up
PDF
Holacracy
PDF
AWS IAM
PDF
PDF
Encryption Deep Dive
PDF
Sec 101
PDF
Reflections on SCM
PDF
Management: Doing the non-obvious! III
PDF
Design is not Subjective
PDF
Architecture & Engineering : Doing the non-obvious!
PDF
Management doing the non-obvious II
PDF
Testing in production
PDF
Nine lies about work
PDF
Management: doing the nonobvious!
PDF
AI and the Future
PDF
Dealing with dependencies
PDF
Dealing with dependencies in tests
PDF
Kanban 2020
Naming Things Book : Simple Book Review!
Continuous Discovery Habits Book Review.pdf
Thoughts about Shape Up
Holacracy
AWS IAM
Encryption Deep Dive
Sec 101
Reflections on SCM
Management: Doing the non-obvious! III
Design is not Subjective
Architecture & Engineering : Doing the non-obvious!
Management doing the non-obvious II
Testing in production
Nine lies about work
Management: doing the nonobvious!
AI and the Future
Dealing with dependencies
Dealing with dependencies in tests
Kanban 2020

Spring Capitulo 05

  • 1.  
  • 2.  
  • 3. Conhecer as facilidades de e-mails do Spring Saber agendar tarefas com JDK Task Saber interceptar métodos com AOP Saber montar um contexto de teste com JUnit Saber expor serviço via RMI
  • 4. Depedências: mail.jar activation.jar MailSender Hierarquia de exceptions:
  • 5. Funcionalidades especializadas para o envio de e-mail com suporte MIME(MimeMessagePreparator) < bean id = &quot;mailSender&quot; class = &quot;org.springframework.mail.javamail.JavaMailSenderImpl&quot; > < property name = &quot;host&quot; value = &quot;host.url.com.br&quot; /> < property name = &quot;password&quot; value = &quot;senha&quot; /> < property name = &quot;username&quot; value = &quot;username@host.com.br&quot; /> </ bean > < bean id = &quot;simpleMailMessage&quot; class = &quot;org.springframework.mail.SimpleMailMessage&quot; > < constructor-arg index = &quot;0&quot; ref = &quot;templateMessage&quot; /> < property name = &quot;to&quot; value = &quot;to@server.com&quot; /> < property name = &quot;text&quot; value = &quot; 123 Testando... &quot; /> </ bean >
  • 6. package com.targettrust.spring.email; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; public class TesteEnviaEmail { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; ); SimpleMailMessage msg = (SimpleMailMessage)ac.getBean( &quot;simpleMailMessage&quot; ); MailSender ms = (MailSender)ac.getBean( &quot;mailSender&quot; ); try { ms.send(msg); } catch (MailException ex) { ex.printStackTrace(); } } }
  • 7. package com.targettrust.spring.email; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; public class TesteMimeMessageHelperAtt { public static void main( String [] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; ); JavaMailSender ms = (JavaMailSender)ac.getBean( &quot;mailSender&quot; ); try { MimeMessage message = ms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true ); helper.setFrom( &quot;from@server.com.br&quot; ); helper.setTo( &quot;to@server.com&quot; ); helper.setText( &quot;Email MimeMessageHelper&quot; ); FileSystemResource file = new FileSystemResource( new File( &quot;.&quot; ).getCanonicalPath() + &quot;/build.xml&quot; ); helper.addAttachment( &quot;build.xml&quot; , file); ms.send(message); } catch (Exception e){ e.printStackTrace(); } } }
  • 8. package com.targettrust.spring.email; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; public class TesteMimeMessageHelperAttImg { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/email/Spring-beans.xml&quot; ); JavaMailSender ms = (JavaMailSender)ac.getBean( &quot;mailSender&quot; ); try { MimeMessage message = ms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true ); helper.setFrom( &quot;form@server.com.br&quot; ); helper.setTo( &quot;dest@server.com&quot; ); helper.setText( &quot;<html><body><img src='cid:img1'><br>Email MimeMessageHelper com suporte a imagems em linha!</body></html>&quot; , true ); FileSystemResource file = new FileSystemResource( new File( &quot;.&quot; ).getCanonicalPath() + &quot;/imagem.jpg&quot; ); helper.addInline( &quot;img1&quot; , file); ms.send(message); } catch (Exception e){ e.printStackTrace(); } } }
  • 9. Agendamento de Tarefas Utiliza beans Execução de tempos em tempos Ecolha: menos XML VS menos Acoplamento Timer JDK
  • 10. package com.targettrust.spring.jdktask; import java.util.Date; import java.util.TimerTask; public class HoraCertaService extends TimerTask{ @Override @SuppressWarnings ( &quot;deprecation&quot; ) public void run() { System. out .println( new Date().getHours() + &quot;:&quot; + new Date().getMinutes() + &quot;:&quot; + new Date().getSeconds() ); } }
  • 11. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;horaCertaService&quot; class = &quot;com.targettrust.spring.jdktask.HoraCertaService&quot; /> < bean id = &quot;scheduledTask&quot; class = &quot;org.springframework.scheduling.timer.ScheduledTimerTask&quot; lazy-init = &quot;false&quot; > <!-- Espera 0 ms antes de iniciar --> < property name = &quot;delay&quot; value = &quot;0&quot; /> <!-- roda de 1 em 1 segundo --> < property name = &quot;period&quot; value = &quot;1000&quot; /> <!-- Ira executar a TimerTask horaCertaService --> < property name = &quot;timerTask&quot; ref = &quot;horaCertaService&quot; /> </ bean > </ beans >
  • 12. < bean id = &quot;timerFactory“ class = &quot;org.springframework.scheduling.timer.TimerFactoryBean” > < property name = &quot;scheduledTimerTasks&quot; > < list > < ref bean = &quot;scheduledTask&quot; /> </ list > </ property > </ bean >
  • 13. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;horaCertaServiceNaoAcoplada&quot; class = &quot;com.targettrust.spring.jdktask.HoraCertaServiceNaoAcoplada“ /> < bean id = &quot;scheduledTask“ lazy-init = &quot;false&quot; class = &quot;org.springframework.scheduling.timer.ScheduledTimerTask” > <!-- Espera 0 ms antes de iniciar --> < property name = &quot;delay&quot; value = &quot;0&quot; /> <!-- roda de 1 em 1 segundo --> < property name = &quot;period&quot; value = &quot;1000&quot; /> <!-- Ira executar a TimerTask horaCertaService --> < property name = &quot;timerTask&quot; ref = &quot;executor&quot; /> </ bean > < bean id = &quot;executor&quot; class = &quot;org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean“ > < property name = &quot;targetObject&quot; ref = &quot;horaCertaServiceNaoAcoplada&quot; /> < property name = &quot;targetMethod&quot; value = &quot;showTime&quot; /> </ bean > < bean id = &quot;timerFactory&quot; class = &quot;org.springframework.scheduling.timer.TimerFactoryBean“ > < property name = &quot;scheduledTimerTasks&quot; > < list > < ref bean = &quot;scheduledTask&quot; /> </ list > </ property > </ bean > </ beans >
  • 14. Utiliza AOP com AspectJ Abstrações sobre o AspectJ Weaving em runtime Dependências: aspectjweaver.jar aspectjrt.jar
  • 15.  
  • 16.  
  • 17. package com.targettrust.spring.aop; public interface Service { public void fazAlgo(); } package com.targettrust.spring.aop; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ServiceA implements Service{ private static final Log log = LogFactory. getLog (ServiceA. class ); @Override public void fazAlgo() { log .info( &quot;Fiz algo do tipo A&quot; ); } } package com.targettrust.spring.aop; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ServiceB implements Service{ private static final Log log = LogFactory. getLog (ServiceB. class ); @Override public void fazAlgo() { log .info( &quot;Fiz algo do tipo B&quot; ); } }
  • 18. package com.targettrust.spring.aop; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ServiceC implements Service{ private static final Log log = LogFactory. getLog (ServiceC. class ); @Override public void fazAlgo() { log .info( &quot;Fiz algo do tipo C&quot; ); } }
  • 19. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:aop = &quot;http://www.springframework.org/schema/aop&quot; xmlns:tx = &quot;http://www.springframework.org/schema/tx&quot; xsi:schemaLocation = &quot; http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot; > < aop:aspectj-autoproxy /> < bean id = &quot;aspecto“ lazy-init = &quot;false&quot; class = &quot;com.targettrust.spring.aop.Aspecto“ /> < bean id = &quot;sa“ class = &quot;com.targettrust.spring.aop.ServiceA“ /> < bean id = &quot;sb“ class = &quot;com.targettrust.spring.aop.ServiceB“ /> < bean id = &quot;sc“ class = &quot;com.targettrust.spring.aop.ServiceC“ /> < bean id = &quot;services“ class = &quot;java.util.ArrayList“ > < constructor-arg index = &quot;0&quot; > < list > < ref bean = &quot;sa&quot; /> < ref bean = &quot;sb&quot; /> < ref bean = &quot;sc&quot; /> </ list > </ constructor-arg > </ bean > </ beans >
  • 20. package com.targettrust.spring.aop; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class Aspecto { private static final Log log = LogFactory. getLog (Aspecto. class ); @Before ( &quot;execution(* com.targettrust.spring.aop.Service.*(..))&quot; ) public void execucaoDeFazAlgoAntes() { log .info( &quot;To sabendo antes da execu ç ão de Service&quot; ); } @After ( &quot;execution(* com.targettrust.spring.aop.Service.*(..))&quot; ) public void execucaoDeFazAlgoDepois() { log .info( &quot;To sabendo depois da execu ç ão de Serice&quot; ); } @Around ( &quot;execution(* com.targettrust.spring.aop.ServiceB.faz*(..)))&quot; ) public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { Object retVal = pjp.proceed(); log .info( &quot;To sabendo around SericeB&quot; ); return retVal; } }
  • 21. Integração com Junit e TestNG Auto-injeção de propriedades Rollback automático após o teste Prove testes integrados sem servidor de aplicação, mas usando transação e banco de dados. Cache
  • 22. AbstractDependencyInjectionSpringContextTests AbstractAnnotationAwareTransactionalTests: @DirtiesContext : Annotation que faz o mesmo que o método setDirty isso fará que o contexto seja recarregado nesse método. @ExpectedException: Annotation que sinaliza que o método deve retornar um exception específica, se ele não retornar o teste irá falhar. @NotTransactionl : Indica que esse método roda fora do contexto de transações do Spring. @Repeat : Essa annotation recebe um número, por exemplo 5. O Spring irá repitir esse teste 5 vezes. AbstractTransactionalDataSourceSpringContextTests
  • 23. package com.targettrust.spring.testing; import java.util.Date; import junit.framework.Assert; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; public class TestDataService extends AbstractDependencyInjectionSpringContextTests { private DataService dataService ; public void setDataService(DataService dataService) { this . dataService = dataService; } @Override protected String[] getConfigLocations() { return new String[]{ &quot;classpath:com/targettrust/spring/testing/Spring-beans.xml&quot; }; } @SuppressWarnings ( &quot;deprecation&quot; ) public void testDataDoDataService(){ Date d = dataService .getSysDate(); Date l = new Date(); Assert. assertEquals (d.getDay(),l.getDay()); Assert. assertEquals (d.getMonth(),l.getMonth()); Assert. assertEquals (d.getYear(),l.getYear()); } }
  • 24. Exposição de beans Pode ser: RMI, JAX-RPC, JMS, Hessian, Burlap, Http Invoker e até mesmo EJB. Para RMI: Serializable Porta na máquina Abstração sob o RMI
  • 25. package com.targettrust.spring.remoting; import java.util.Date; public interface HoraService { public Date getDate(); } package com.targettrust.spring.remoting; import java.util.Calendar; import java.util.Date; public class HoraServiceImpl implements HoraService{ public Date getDate() { return Calendar. getInstance ().getTime(); } } <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;horaService&quot; class = &quot;com.targettrust.spring.remoting.HoraServiceImpl” /> < bean class = &quot;org.springframework.remoting.rmi.RmiServiceExporter” > < property name = &quot;serviceName&quot; value = &quot;Target-HoraService&quot; /> < property name = &quot;service&quot; ref = &quot;horaService&quot; /> < property name = &quot;serviceInterface“ value = &quot;com.targettrust.spring.remoting.HoraService&quot; /> < property name = &quot;registryPort&quot; value = &quot;1199&quot; /> </ bean > </ beans >
  • 26. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = “ http://www.springframework.org/schema/beans ” xmlns:xsi = “ http://www.w3.org/2001/XMLSchema-instance ” xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;horaService” class = &quot;org.springframework.remoting.rmi.RmiProxyFactoryBean&quot; > < property name = &quot;serviceUrl&quot; value = &quot;rmi://localhost:1199/Target-HoraService&quot; /> < property name = &quot;serviceInterface&quot; value = &quot;com.targettrust.spring.remoting.HoraService&quot; /> </ bean > </ beans >
  • 27. Crie um Aspecto para logar todas as chamadas aos dados de um sistema Crie um agendamento com JDK Task que de 5 em 5 segundos manda um e-mail para uma pessoa informando se ouve alguma mudança no sistema. Crie um serviço de calculadora e exporte ele via RMI, faça um porgrama cliente com o suporte de Junit do Spring e suas classes de teste.