Your SlideShare is downloading. ×
0
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Spring Capitulo 03
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Spring Capitulo 03

5,546

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
5,546
On Slideshare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
153
Comments
0
Likes
0
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.  
  • 2.  
  • 3. <ul><li>Conhecer os resource loaders do Spring </li></ul><ul><li>Saber utilizar o init-method </li></ul><ul><li>Saber utilizar a herança de definições de beans </li></ul><ul><li>Saber fazer classes de validações </li></ul><ul><li>Conhecer o BeanWrapper </li></ul><ul><li>Conhecer os PostProcessors </li></ul>
  • 4. <ul><li>Conhecer os principais properties editors </li></ul><ul><li>Conhecer os eventos do container </li></ul><ul><li>Saber utilizar o PropertyPlaceHolderConfigurer </li></ul><ul><li>Saber utilizar o SingletonBeanFactoryLocator </li></ul><ul><li>Conhecer os recursos de i18n </li></ul>
  • 5. <ul><ul><li>ResourcePatternResolver(ant style) </li></ul></ul><ul><ul><li>file: </li></ul></ul><ul><ul><li>classpath: </li></ul></ul><ul><ul><li>wild-cards /* </li></ul></ul><ul><ul><li>ServletContextResourceLoader </li></ul></ul><ul><ul><li>Extensível, criar seu próprio </li></ul></ul>
  • 6. <ul><li>init-method </li></ul><ul><ul><li>Executa método ao iniciar </li></ul></ul><ul><ul><li>init-method=“voidMethod” </li></ul></ul><ul><ul><li>Método público e void </li></ul></ul><ul><li>Callbacks do Spring: </li></ul><ul><ul><li>InitializingBean </li></ul></ul><ul><ul><ul><li>afterPropertiesSet </li></ul></ul></ul><ul><ul><li>DisposableBean </li></ul></ul><ul><ul><ul><li>destroy </li></ul></ul></ul>
  • 7. <ul><li>Dois colaboradores ou mais </li></ul><ul><li>Propriedades abstract e parent </li></ul><ul><li>Estrutura de Herança </li></ul><ul><li>Reaproveitamento de injeções </li></ul>
  • 8. package com.targettrust.spring.extend; public abstract class PessoaService { private String nome ; private String telefone ; private String email ; public PessoaService() {} public String getNome() { return nome ; } public void setNome(String nome) { this . nome = nome; } public String getTelefone() { return telefone ; } public void setTelefone(String telefone) { this . telefone = telefone; } public String getEmail() { return email ; } public void setEmail(String email) { this . email = email; } }
  • 9. package com.targettrust.spring.extend; public class PessoaFisicaService extends PessoaService { private String cpf ; public PessoaFisicaService() {} public boolean validaCpf(){ return CpfUtils. validaCPF ( cpf ); } public void mostraPessoa(){ if (validaCpf()){ System. out .println( &amp;quot;nome: &amp;quot; + getNome() + &amp;quot; telefone: &amp;quot; + getTelefone() + &amp;quot; email: &amp;quot; + getEmail() + &amp;quot; cpf: &amp;quot; + cpf ); } else { System. out .println( &amp;quot;Essa pessoa não tem um CPF Valido.&amp;quot; ); } } public String getCpf() { return cpf ; } public void setCpf(String cpf) { this . cpf = cpf; } }
  • 10. package com.targettrust.spring.extend; public class PessoaFisicaService extends PessoaService { private String cpf ; public PessoaFisicaService() {} public boolean validaCpf(){ return CpfUtils. validaCPF ( cpf ); } public void mostraPessoa(){ if (validaCpf()){ System. out .println( &amp;quot;nome: &amp;quot; + getNome() + &amp;quot; telefone: &amp;quot; + getTelefone() + &amp;quot; email: &amp;quot; + getEmail() + &amp;quot; cpf: &amp;quot; + cpf ); } else { System. out .println( &amp;quot;Essa pessoa não tem um CPF Valido.&amp;quot; ); } } public String getCpf() { return cpf ; } public void setCpf(String cpf) { this . cpf = cpf; } }
  • 11. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; &gt; &lt; bean id = &amp;quot;pessoaService&amp;quot; class = &amp;quot;com.targettrust.spring.extend.PessoaService&amp;quot; abstract = &amp;quot;true&amp;quot; &gt; &lt; property name = &amp;quot;nome&amp;quot; value = &amp;quot;Diego&amp;quot; /&gt; &lt; property name = &amp;quot;email&amp;quot; value = &amp;quot;pacheco@diego.com.spring&amp;quot; /&gt; &lt; property name = &amp;quot;telefone&amp;quot; value = &amp;quot;455-55-55&amp;quot; /&gt; &lt;/ bean &gt; &lt; bean abstract = &amp;quot;false&amp;quot; id = &amp;quot;pessoaFisicaService&amp;quot; class = &amp;quot;com.targettrust.spring.extend.PessoaFisicaService&amp;quot; parent = &amp;quot;pessoaService&amp;quot; &gt; &lt; property name = &amp;quot;cpf&amp;quot; value = &amp;quot;47888971210&amp;quot; /&gt; &lt;/ bean &gt; &lt;/ beans &gt;
  • 12. <ul><li>Interface Validor </li></ul><ul><ul><li>boolean supports (Class clazz); </li></ul></ul><ul><ul><li>void validate (Object target, Errors errors); </li></ul></ul><ul><li>VadationUtils </li></ul><ul><ul><li>rejectIfEmpty </li></ul></ul><ul><ul><li>rejectValue </li></ul></ul><ul><ul><li>Retorno de erro via objeto (Spring MVC, tags de tela) </li></ul></ul>
  • 13. package com.targettrust.spring.validate; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class Pessoa implements Validator{ private String nome ; private Integer idade ; public boolean supports(Class clazz) { return Pessoa. class .equals(clazz); } public void validate(Object target, Errors errors) { ValidationUtils. rejectIfEmpty (errors, &amp;quot;nome&amp;quot; , &amp;quot;nome.vazio&amp;quot; ); Pessoa p = (Pessoa) target; if (p.getIdade() &lt; 0) { errors.rejectValue( &amp;quot;idade&amp;quot; , &amp;quot;valor negativo&amp;quot; ); } else if (p.getIdade() &gt; 120) { errors.rejectValue( &amp;quot;idade&amp;quot; , &amp;quot;velho de mais&amp;quot; ); } } public String getNome() { return nome ; } public void setNome(String nome) { this . nome = nome; } public Integer getIdade() { return idade ; } public void setIdade(Integer idade) { this . idade = idade; } }
  • 14. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; default-lazy-init = &amp;quot;true&amp;quot; &gt; &lt; bean id = &amp;quot;pessoa&amp;quot; class = &amp;quot;com.targettrust.spring.validate.Pessoa&amp;quot; &gt; &lt; property name = &amp;quot;nome&amp;quot; value = &amp;quot;Fulano&amp;quot; /&gt; &lt; property name = &amp;quot;idade&amp;quot; value = &amp;quot;-1&amp;quot; /&gt; &lt;/ bean &gt; &lt;/ beans &gt;
  • 15. package com.targettrust.spring.validate; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; public class Teste { public static void main(String[] args) { BeanFactory bf = new ClassPathXmlApplicationContext( &amp;quot;/com/targettrust/spring/validate/Spring-beans.xml&amp;quot; ); Pessoa p = (Pessoa) bf.getBean( &amp;quot;pessoa&amp;quot; ); System. out .println( &amp;quot;Nome: &amp;quot; + p.getNome() + &amp;quot; idade: &amp;quot; + p.getIdade()); Errors e = new BeanPropertyBindingResult(p, &amp;quot;Pessoa&amp;quot; ); p.validate(p, e); for (Object es: e.getAllErrors()){ System. out .println(es); } } } Chamada manual !!!
  • 16. <ul><li>Wrapper de JavaBeans </li></ul><ul><li>Pattern GoF Decorator </li></ul><ul><li>Acesso a propriedade de objetos: </li></ul><ul><ul><li>Getters </li></ul></ul><ul><ul><li>Setters </li></ul></ul><ul><ul><li>Pode escrever? </li></ul></ul><ul><ul><li>Pode Ler? </li></ul></ul>
  • 17. <ul><li>Acesso a sub-propriedades de profundidade ilimitada </li></ul><ul><li>Manipulação com propriedades de maneira elegante </li></ul><ul><li>Implementação padrão: BeanWrapperImpl </li></ul><ul><li>PropertyDescriptor </li></ul>
  • 18. &nbsp;
  • 19. <ul><li>Customização de beans através de Callbacks </li></ul><ul><li>Forma de extenção do Spring para: </li></ul><ul><ul><li>Lógica de instanciação </li></ul></ul><ul><ul><li>Lógica de resolução de dependências </li></ul></ul><ul><ul><li>Operações em geral após a etapa de registro de beans do Spring </li></ul></ul>
  • 20. <ul><li>Múltiplos BeanPostProcessors </li></ul><ul><li>Efetuar a ordem de execução através da propriedade order, implementar a interface Ordered </li></ul><ul><li>Atuação: Após a criação do bean </li></ul><ul><li>Executado antes de init-methods </li></ul>
  • 21. <ul><li>ApplicationContext: Registro automático </li></ul><ul><li>BeanFactory: Registro manual </li></ul><ul><li>São trados de maneira especial: “Toca inicializa” </li></ul>ConfigurableBeanFactory factory = new XmlBeanFactory( new ClassPathResource( &amp;quot;beans.xml&amp;quot; )); MeuBeanPostProcessor postProcessor = new MeuBeanPostProcessor(); factory.addBeanPostProcessor(postProcessor);
  • 22. <ul><li>Cuidado com AOP Auto-proxy: Bean não elegíveis, Spring emitirá um alerta </li></ul><ul><li>Veja um exemplo de BeanPostProcessor: </li></ul>package com.targettrust.spring.beanpostprocessors; public class ObjetoA { } package com.targettrust.spring.beanpostprocessors; public class ObjetoB { } package com.targettrust.spring.beanpostprocessors; public class ObjetoC { }
  • 23. package com.targettrust.spring.beanpostprocessors; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class LogCreationBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System. out .println( &amp;quot;Craindo bean: &amp;quot; + beanName); return bean; } }
  • 24. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; default-lazy-init = &amp;quot;false&amp;quot; &gt; &lt; bean id = &amp;quot;a&amp;quot; class = &amp;quot;com.targettrust.spring.beanpostprocessors.ObjetoA&amp;quot; /&gt; &lt; bean id = &amp;quot;b&amp;quot; class = &amp;quot;com.targettrust.spring.beanpostprocessors.ObjetoB&amp;quot; /&gt; &lt; bean id = &amp;quot;c&amp;quot; class = &amp;quot;com.targettrust.spring.beanpostprocessors.ObjetoC&amp;quot; /&gt; &lt; bean class = &amp;quot;com.targettrust.spring.beanpostprocessors.LogCreationBeanPostProcessor” /&gt; &lt;/ beans &gt;
  • 25. package com.targettrust.spring.beanpostprocessors; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Teste { public static void main(String[] args) { new ClassPathXmlApplicationContext( &amp;quot;/com/targettrust/spring/&amp;quot; + &amp;quot;beanpostprocessors/Spring-beans.xml&amp;quot; ); } }
  • 26. <ul><li>Recebe o Objeto, então podemos: </li></ul><ul><ul><li>Aplicar algum proxy </li></ul></ul><ul><ul><li>Aplicar algum validador </li></ul></ul><ul><ul><li>Poder: Annotations + interface + BeanPostProcessor </li></ul></ul>
  • 27. <ul><li>Similar ao BeanPostProcessor </li></ul><ul><li>Pode ler metadados do Spring </li></ul><ul><li>Possibilidade de modificação de dados(informações injetadas) </li></ul><ul><li>Spring utiliza no core: </li></ul><ul><ul><li>PropertyResourceConfigurer </li></ul></ul><ul><ul><li>PropertyPlaceHolderConfigurer </li></ul></ul>
  • 28. package com.targettrust.spring.beanfactorypostprocessors; import java.text.SimpleDateFormat; import java.util.Date; public class DataService { private String pattern ; public String getPattern() { return pattern ; } public void setPattern(String pattern) { this . pattern = pattern; } public String showSysDate(){ SimpleDateFormat sdf = new SimpleDateFormat( pattern ); return sdf.format( new Date()); } }
  • 29. package com.targettrust.spring.beanfactorypostprocessors; import java.io.FileInputStream; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class DatePatternRouterBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { Properties p = new Properties(); try { p.load( new FileInputStream( &amp;quot;./src/com/targettrust/spring/” + beanfactorypostprocessors/patterns.properties&amp;quot; )); System. out .println( &amp;quot;Patterns: &amp;quot; + p); } catch (Exception e) { throw new FatalBeanException( &amp;quot;Erro ao buscar patterns!&amp;quot; ,e); } Map&lt;Object,Object&gt; beans = beanFactory.getBeansOfType(DataService. class ); for (Entry&lt;Object, Object&gt; e: beans.entrySet()){ System. out .println( &amp;quot;Aplicando pattern em service: &amp;quot; + e); DataService service = ((DataService)e.getValue()); service.setPattern(p.getProperty( &amp;quot;pattern.&amp;quot; + service.getPattern().replace( &amp;quot;#&amp;quot; , &amp;quot;&amp;quot; ))); } } }
  • 30. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; default-lazy-init = &amp;quot;false&amp;quot; &gt; &lt; bean id = &amp;quot;brasilDateService&amp;quot; class = &amp;quot;com.targettrust.spring.beanfactorypostprocessors.DataService&amp;quot; &gt; &lt; property name = &amp;quot;pattern&amp;quot; value = &amp;quot;#brasil&amp;quot; /&gt; &lt;/ bean &gt; &lt; bean id = &amp;quot;usDateService&amp;quot; class = &amp;quot;com.targettrust.spring.beanfactorypostprocessors.DataService&amp;quot; &gt; &lt; property name = &amp;quot;pattern&amp;quot; value = &amp;quot;#us&amp;quot; /&gt; &lt;/ bean &gt; &lt; bean class = &amp;quot;com.targettrust.spring.beanfactorypostprocessors.DatePatternRouterBeanFactoryPostProcessor&amp;quot; /&gt; &lt;/ beans &gt;
  • 31. package com.targettrust.spring.beanfactorypostprocessors; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Teste { public static void main(String[] args) { ApplicationContext ap = new ClassPathXmlApplicationContext( &amp;quot;/com/targettrust/spring/beanfactorypostprocessors/Spring-beans.xml&amp;quot; ); System. out .println( &amp;quot;Data Brasil pattern : &amp;quot; + ((DataService)ap.getBean( &amp;quot;brasilDateService&amp;quot; )).showSysDate()); System. out .println( &amp;quot;Data Us pattern : &amp;quot; + (DataService)ap.getBean( &amp;quot;usDateService&amp;quot; )).showSysDate()); } }
  • 32. <ul><li>Muito utilizado </li></ul><ul><li>Convertem a informação para o tipo de dado correto. </li></ul><ul><li>Deixa o XML menos verbose </li></ul><ul><li>Padroniza e prove produtividade </li></ul>&lt; bean id = &amp;quot;txt&amp;quot; class = &amp;quot;java.io.File&amp;quot; &gt; &lt; constructor-arg index = &amp;quot;0&amp;quot; value = &amp;quot;C:/BOOTSECT.BAK&amp;quot; /&gt; &lt;/ bean &gt;
  • 33. &nbsp;
  • 34. &nbsp;
  • 35. &nbsp;
  • 36. <ul><li>PropertyEditorManager(java, procurar) </li></ul><ul><li>Localização automática </li></ul><ul><ul><li>Foo </li></ul></ul><ul><ul><li>FooEditor </li></ul></ul><ul><ul><li>Extensível: PropertyEditorSupport </li></ul></ul>
  • 37. package com.targettrust.spring.propertyeditor; public class Aluno { private String nome ; public Aluno() {} public Aluno(String nome) { super (); this . nome = nome; } public String getNome() { return nome ; } public void setNome(String nome) { this . nome = nome; } @Override public String toString() { return nome ; } }
  • 38. package com.targettrust.spring.propertyeditor; import java.util.List; public class Turma { private String nome ; private List&lt;Aluno&gt; alunos ; public Turma() {} public Turma(String nome, List&lt;Aluno&gt; alunos) { super (); this . nome = nome; this . alunos = alunos; } public String getNome() { return nome ; } public void setNome(String nome) { this . nome = nome; } public List&lt;Aluno&gt; getAlunos() { return alunos ; } public void setAlunos(List&lt;Aluno&gt; alunos) { this . alunos = alunos; } @Override public String toString() { return nome + &amp;quot; alunos: &amp;quot; + alunos .toString(); } }
  • 39. package com.targettrust.spring.propertyeditor; import java.beans.PropertyEditorSupport; public class AlunoEditor extends PropertyEditorSupport{ @Override public void setAsText(String text) throws IllegalArgumentException { Aluno a = new Aluno(text); setValue(a); } }
  • 40. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; &gt; &lt; bean id = &amp;quot;turma“ class = &amp;quot;com.targettrust.spring.propertyeditor.Turma&amp;quot; &gt; &lt; property name = &amp;quot;nome&amp;quot; value = &amp;quot;Curso-Spring&amp;quot; /&gt; &lt; property name = &amp;quot;alunos&amp;quot; &gt; &lt; list &gt; &lt; value &gt; Rod &lt;/ value &gt; &lt; value &gt; Joe &lt;/ value &gt; &lt; value &gt; Bart &lt;/ value &gt; &lt; value &gt; Homer &lt;/ value &gt; &lt; value &gt; Hammer &lt;/ value &gt; &lt;/ list &gt; &lt;/ property &gt; &lt;/ bean &gt; &lt; bean id = &amp;quot;customEditorConfigurer“ class = &amp;quot;org.springframework.beans.factory.config.CustomEditorConfigurer“ &gt; &lt; property name = &amp;quot;customEditors&amp;quot; &gt; &lt; map &gt; &lt; entry key = &amp;quot;com.targettrust.spring.propertyeditor.Aluno&amp;quot; &gt; &lt; bean class = &amp;quot;com.targettrust.spring.propertyeditor.AlunoEditor&amp;quot; /&gt; &lt;/ entry &gt; &lt;/ map &gt; &lt;/ property &gt; &lt;/ bean &gt; &lt;/ beans &gt;
  • 41. <ul><li>Só no ApplicationContext </li></ul><ul><li>ApplicationEvent </li></ul><ul><li>ApplicationListener </li></ul><ul><li>Toda vez que um ApplicationEvent é disparado seu ApplicationListener é notificado recebendo o evento. </li></ul><ul><li>Sincronos (Bloqueio do Spring até o fim de todos) </li></ul>
  • 42. &nbsp;
  • 43. package com.targettrust.spring.event; import org.springframework.context.ApplicationEvent; public class FeriadoEvent extends ApplicationEvent{ private String data ; private static final long serialVersionUID = 1L; public FeriadoEvent(Object source,String data) { super (source); this . data = data; } public String getData() { return data ; } }
  • 44. package com.targettrust.spring.event; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class FeriadoListener implements ApplicationListener { public void onApplicationEvent(ApplicationEvent event) { if (event instanceof FeriadoEvent){ FeriadoEvent fe = (FeriadoEvent)event; System. out .println( &amp;quot;Viva! Dia: &amp;quot; + fe.getData() + &amp;quot; é feriado. Uhhuu!!!&amp;quot; ); } } }
  • 45. package com.targettrust.spring.event; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class RH implements ApplicationContextAware { private ApplicationContext ac ; public void pulicarFeriados(){ ac .publishEvent( new FeriadoEvent( this , &amp;quot;01/01/08&amp;quot; )); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ac = applicationContext; } }
  • 46. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; &gt; &lt; bean id = &amp;quot;rh&amp;quot; class = &amp;quot;com.targettrust.spring.event.RH&amp;quot; /&gt; &lt; bean id = &amp;quot;funcionarioEsperto &amp;quot; class = &amp;quot;com.targettrust.spring.event.FeriadoListener&amp;quot; /&gt; &lt;/ beans &gt;
  • 47. package com.targettrust.spring.event; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Teste { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( &amp;quot;/com/targettrust/spring/event/Spring-beans.xml&amp;quot; ); RH rh = (RH)ac.getBean( &amp;quot;rh&amp;quot; ); rh.pulicarFeriados(); } }
  • 48. <ul><li>Externalizar informações na BF </li></ul><ul><li>É um BeanFactoryPostProcessor </li></ul><ul><li>Externalização em .properties </li></ul><ul><li>Útil para: </li></ul><ul><ul><li>Conexões de banco </li></ul></ul><ul><ul><li>Usuários </li></ul></ul><ul><ul><li>Listas de e-mails </li></ul></ul><ul><ul><li>Evita mexer no XML, diminui erros </li></ul></ul>
  • 49. <ul><li>Procura nas propriedades do sistema de modo: systemPropertiesMode </li></ul><ul><li>Excelente para realizar roteamentos </li></ul><ul><li>Diminui o volume de dados em XML </li></ul><ul><li>Aceita Property em linha, dupla flexibilidade </li></ul>
  • 50. package com.targettrust.spring.propertyplaceholderconfigurer; public class Instrutor { private String nome ; private int idade ; private String time ; private float altura ; // getters and Setters } nome = deigo idade = 22 altura = 1.85 Arquivo .properties
  • 51. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; &gt; &lt; bean class = &amp;quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&amp;quot; &gt; &lt; property name = &amp;quot;location“ &gt; &lt; value &gt; classpath:com/targettrust/spring/propertyplaceholderconfigurer/config.properties &lt;/ value &gt; &lt;/ property &gt; &lt; property name = &amp;quot;properties&amp;quot; &gt; &lt; value &gt; time=Grêmio &lt;/ value &gt; &lt;/ property &gt; &lt;/ bean &gt; &lt; bean id = &amp;quot;I” class = &amp;quot;com.targettrust.spring.propertyplaceholderconfigurer.Instrutor&amp;quot; &gt; &lt; property name = &amp;quot;nome&amp;quot; value = &amp;quot;${nome}&amp;quot; /&gt; &lt; property name = &amp;quot;idade&amp;quot; value = &amp;quot;${idade}&amp;quot; /&gt; &lt; property name = &amp;quot;time&amp;quot; value = &amp;quot;${time}&amp;quot; /&gt; &lt; property name = &amp;quot;altura&amp;quot; value = &amp;quot;${altura}&amp;quot; /&gt; &lt;/ bean &gt; &lt;/ beans &gt;
  • 52. <ul><li>Permite carregar múltiplos arquivos de configurações de uma só vez </li></ul><ul><li>Aplicação dividida em camadas </li></ul><ul><li>Cuidado ao utilizar: veja JEE </li></ul><ul><li>Cada camada é uma BeanFactory </li></ul><ul><li>XML na raiz do cp com nome: beanRefFactory.xml </li></ul>
  • 53. package com.targettrust.spring.singletonbeanfactorylocator; public class ObjetoA {} &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; default-lazy-init = &amp;quot;true&amp;quot; &gt; &lt; bean id = &amp;quot;A1&amp;quot; class = &amp;quot;com.targettrust.spring.singletonbeanfactorylocator.ObjetoA” /&gt; &lt;/ beans &gt; + A2 A3 A4
  • 54. &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; default-lazy-init = &amp;quot;false&amp;quot; &gt; &lt; bean id = &amp;quot;beanFactoryBean“ class = &amp;quot;org.springframework.context.support.ClassPathXmlApplicationContext” &gt; &lt; constructor-arg &gt; &lt; list &gt; &lt; value &gt; com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-A.xml &lt;/ value &gt; &lt; value &gt; com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-B.xml &lt;/ value &gt; &lt; value &gt; com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-C.xml &lt;/ value &gt; &lt;/ list &gt; &lt;/ constructor-arg &gt; &lt;/ bean &gt; &lt; bean id = &amp;quot;beanFactoryBean2“ class = &amp;quot;org.springframework.context.support.ClassPathXmlApplicationContext“ &gt; &lt; constructor-arg &gt; &lt; list &gt; &lt; value &gt; com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-D.xml &lt;/ value &gt; &lt;/ list &gt; &lt;/ constructor-arg &gt; &lt;/ bean &gt; &lt;/ beans &gt;
  • 55. package com.targettrust.spring.singletonbeanfactorylocator; import org.springframework.beans.factory.access.BeanFactoryLocator; import org.springframework.beans.factory.access.BeanFactoryReference; import org.springframework.beans.factory.access.SingletonBeanFactoryLocator; public class Teste { public static void main(String[] args) { BeanFactoryLocator bfl = SingletonBeanFactoryLocator. getInstance (); BeanFactoryReference bf = bfl.useBeanFactory( &amp;quot;beanFactoryBean&amp;quot; ); ObjetoA a1 = (ObjetoA)bf.getFactory().getBean( &amp;quot;A1&amp;quot; ); ObjetoA a2 = (ObjetoA)bf.getFactory().getBean( &amp;quot;A2&amp;quot; ); ObjetoA a3 = (ObjetoA)bf.getFactory().getBean( &amp;quot;A3&amp;quot; ); bf = bfl.useBeanFactory( &amp;quot;beanFactoryBean2&amp;quot; ); ObjetoA a4 = (ObjetoA)bf.getFactory().getBean( &amp;quot;A4&amp;quot; ); System. out .println( &amp;quot;ObjetoA a1: &amp;quot; + a1); System. out .println( &amp;quot;ObjetoA a2: &amp;quot; + a2); System. out .println( &amp;quot;ObjetoA a3: &amp;quot; + a3); System. out .println( &amp;quot;ObjetoA a4: &amp;quot; + a4); } }
  • 56. <ul><li>Somente no ApplicationContext </li></ul><ul><li>Procura por MessageSource </li></ul><ul><li>StaticMessageSource (padrão): </li></ul><ul><ul><li>Programaticamente </li></ul></ul><ul><li>ResourceBundleMessageSource: </li></ul><ul><ul><li>Suporte textFormart </li></ul></ul><ul><ul><li>Carrega arquivos por nome base </li></ul></ul><ul><li>MessageSourceAware </li></ul>
  • 57. package com.targettrust.spring.i18n; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; public class Pessoa implements MessageSourceAware{ private String nome ; private int idade ; private MessageSource ms ; // Getters e Setters public void setIdade( int idade) { if ( idade&lt;=0 || idade &gt;= 120 ) throw new IllegalArgumentException( ms .getMessage( &amp;quot;idade.invalida&amp;quot; , new Object[]{idade},Locale. getDefault ())); this . idade = idade; } }
  • 58. idade.invalida= A idade: {0} não é aceitável por que é muito velha ou menor do que 1 &lt;? xml version = &amp;quot;1.0&amp;quot; encoding = &amp;quot;UTF-8&amp;quot; ?&gt; &lt; beans xmlns = &amp;quot;http://www.springframework.org/schema/beans&amp;quot; xmlns:xsi = &amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xsi:schemaLocation = &amp;quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&amp;quot; &gt; &lt; bean id = &amp;quot;messageSource“ class = &amp;quot;org.springframework.context.support.ResourceBundleMessageSource“ &gt; &lt; property name = &amp;quot;basenames&amp;quot; &gt; &lt; list &gt; &lt; value &gt; mensagems &lt;/ value &gt; &lt;/ list &gt; &lt;/ property &gt; &lt;/ bean &gt; &lt; bean id = &amp;quot;pessoa“ class = &amp;quot;com.targettrust.spring.i18n.Pessoa“ /&gt; &lt;/ beans &gt;
  • 59. package com.targettrust.spring.i18n; import java.util.Locale; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Teste { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( &amp;quot;/com/targettrust/spring/i18n/Spring-beans.xml&amp;quot; ); Locale. setDefault ( new Locale( &amp;quot;pt&amp;quot; , &amp;quot;BR&amp;quot; )); setIdade (ac); } private static void setIdade(ApplicationContext ac){ Pessoa p = (Pessoa)ac.getBean( &amp;quot;pessoa&amp;quot; ); p.setNome( &amp;quot;Crom&amp;quot; ); try { p.setIdade(200); } catch (RuntimeException re){ re.printStackTrace(); } } }
  • 60. <ul><li>Crie um objeto Pessoa: nome, idade, telefone. </li></ul><ul><li>Crie um validador Pessoa </li></ul><ul><li>Invoque o validador de pessoa em um BeanPostProcessor </li></ul><ul><li>Externalize as mensagens de erro em um arquivo property e mostre mensagens i18n caso a idade da pessoa esteja inválida. </li></ul><ul><li>Crie um property editor que seja possível passar o nome, idade e telefone da pessoa apenas na propriedade nome e o property editor espalhará as informações em suas propriedades corretas </li></ul>

×