Your SlideShare is downloading. ×
0
 
 
<ul><li>Conhecer os resource loaders do Spring </li></ul><ul><li>Saber utilizar o init-method </li></ul><ul><li>Saber util...
<ul><li>Conhecer os principais properties editors </li></ul><ul><li>Conhecer os eventos do container </li></ul><ul><li>Sab...
<ul><ul><li>ResourcePatternResolver(ant style) </li></ul></ul><ul><ul><li>file: </li></ul></ul><ul><ul><li>classpath: </li...
<ul><li>init-method </li></ul><ul><ul><li>Executa método ao iniciar </li></ul></ul><ul><ul><li>init-method=“voidMethod” </...
<ul><li>Dois colaboradores ou mais </li></ul><ul><li>Propriedades abstract e parent </li></ul><ul><li>Estrutura de Herança...
package  com.targettrust.spring.extend; public   abstract   class  PessoaService { private  String  nome ; private  String...
package  com.targettrust.spring.extend; public   class  PessoaFisicaService  extends  PessoaService { private  String  cpf...
package  com.targettrust.spring.extend; public   class  PessoaFisicaService  extends  PessoaService { private  String  cpf...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
<ul><li>Interface Validor </li></ul><ul><ul><li>boolean supports (Class clazz); </li></ul></ul><ul><ul><li>void validate (...
package  com.targettrust.spring.validate; import  org.springframework.validation.Errors; import  org.springframework.valid...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
package  com.targettrust.spring.validate; import  org.springframework.beans.factory.BeanFactory; import  org.springframewo...
<ul><li>Wrapper de JavaBeans </li></ul><ul><li>Pattern GoF Decorator </li></ul><ul><li>Acesso a propriedade de objetos: </...
<ul><li>Acesso a sub-propriedades de profundidade ilimitada </li></ul><ul><li>Manipulação com propriedades de maneira eleg...
 
<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><...
<ul><li>Múltiplos BeanPostProcessors </li></ul><ul><li>Efetuar a ordem de execução através da propriedade order, implement...
<ul><li>ApplicationContext: Registro automático </li></ul><ul><li>BeanFactory: Registro manual </li></ul><ul><li>São trado...
<ul><li>Cuidado com AOP Auto-proxy: Bean não elegíveis, Spring emitirá um alerta </li></ul><ul><li>Veja um exemplo de Bean...
package  com.targettrust.spring.beanpostprocessors; import  org.springframework.beans.BeansException; import  org.springfr...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
package  com.targettrust.spring.beanpostprocessors; import  org.springframework.context.support.ClassPathXmlApplicationCon...
<ul><li>Recebe o Objeto, então podemos: </li></ul><ul><ul><li>Aplicar algum proxy </li></ul></ul><ul><ul><li>Aplicar algum...
<ul><li>Similar ao BeanPostProcessor </li></ul><ul><li>Pode ler metadados do Spring </li></ul><ul><li>Possibilidade de mod...
package  com.targettrust.spring.beanfactorypostprocessors; import  java.text.SimpleDateFormat; import  java.util.Date; pub...
package  com.targettrust.spring.beanfactorypostprocessors; import  java.io.FileInputStream; import  java.util.Map; import ...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
package  com.targettrust.spring.beanfactorypostprocessors; import  org.springframework.context.ApplicationContext; import ...
<ul><li>Muito utilizado </li></ul><ul><li>Convertem a informação para o tipo de dado correto. </li></ul><ul><li>Deixa o XM...
 
 
 
<ul><li>PropertyEditorManager(java, procurar) </li></ul><ul><li>Localização automática </li></ul><ul><ul><li>Foo </li></ul...
package  com.targettrust.spring.propertyeditor; public   class  Aluno { private  String  nome ; public  Aluno() {} public ...
package  com.targettrust.spring.propertyeditor; import  java.util.List; public   class  Turma { private  String  nome ; pr...
package  com.targettrust.spring.propertyeditor; import  java.beans.PropertyEditorSupport; public   class  AlunoEditor  ext...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
<ul><li>Só no ApplicationContext </li></ul><ul><li>ApplicationEvent </li></ul><ul><li>ApplicationListener </li></ul><ul><l...
 
package  com.targettrust.spring.event; import  org.springframework.context.ApplicationEvent; public   class  FeriadoEvent ...
package  com.targettrust.spring.event; import  org.springframework.context.ApplicationEvent; import  org.springframework.c...
package  com.targettrust.spring.event; import  org.springframework.beans.BeansException; import  org.springframework.conte...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
package  com.targettrust.spring.event; import  org.springframework.context.ApplicationContext; import  org.springframework...
<ul><li>Externalizar informações na BF </li></ul><ul><li>É um BeanFactoryPostProcessor </li></ul><ul><li>Externalização em...
<ul><li>Procura nas propriedades do sistema de modo:  systemPropertiesMode </li></ul><ul><li>Excelente para realizar rotea...
package  com.targettrust.spring.propertyplaceholderconfigurer; public   class  Instrutor { private  String  nome ; private...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
<ul><li>Permite carregar múltiplos arquivos de configurações de uma  só  vez </li></ul><ul><li>Aplicação dividida em camad...
package  com.targettrust.spring.singletonbeanfactorylocator; public   class  ObjetoA {}   <? xml  version = &quot;1.0&quot...
<? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans  xmlns = &quot;http://www.springframework.org/s...
package  com.targettrust.spring.singletonbeanfactorylocator; import  org.springframework.beans.factory.access.BeanFactoryL...
<ul><li>Somente no ApplicationContext </li></ul><ul><li>Procura por MessageSource </li></ul><ul><li>StaticMessageSource (p...
package  com.targettrust.spring.i18n; import  java.util.Locale; import  org.springframework.context.MessageSource; import ...
idade.invalida= A idade: {0} não é aceitável por que é muito velha ou menor do que 1 <? xml  version = &quot;1.0&quot;  en...
package  com.targettrust.spring.i18n; import  java.util.Locale; import  org.springframework.context.ApplicationContext; im...
<ul><li>Crie um objeto Pessoa:  nome, idade, telefone. </li></ul><ul><li>Crie um validador Pessoa </li></ul><ul><li>Invoqu...
Upcoming SlideShare
Loading in...5
×

Spring Capitulo 03

5,551

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,551
On Slideshare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
153
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Spring Capitulo 03"

  1. 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>
  2. 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>
  3. 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>
  4. 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>
  5. 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>
  6. 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; } }
  7. 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( &quot;nome: &quot; + getNome() + &quot; telefone: &quot; + getTelefone() + &quot; email: &quot; + getEmail() + &quot; cpf: &quot; + cpf ); } else { System. out .println( &quot;Essa pessoa não tem um CPF Valido.&quot; ); } } public String getCpf() { return cpf ; } public void setCpf(String cpf) { this . cpf = cpf; } }
  8. 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( &quot;nome: &quot; + getNome() + &quot; telefone: &quot; + getTelefone() + &quot; email: &quot; + getEmail() + &quot; cpf: &quot; + cpf ); } else { System. out .println( &quot;Essa pessoa não tem um CPF Valido.&quot; ); } } public String getCpf() { return cpf ; } public void setCpf(String cpf) { this . cpf = cpf; } }
  9. 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;pessoaService&quot; class = &quot;com.targettrust.spring.extend.PessoaService&quot; abstract = &quot;true&quot; > < property name = &quot;nome&quot; value = &quot;Diego&quot; /> < property name = &quot;email&quot; value = &quot;pacheco@diego.com.spring&quot; /> < property name = &quot;telefone&quot; value = &quot;455-55-55&quot; /> </ bean > < bean abstract = &quot;false&quot; id = &quot;pessoaFisicaService&quot; class = &quot;com.targettrust.spring.extend.PessoaFisicaService&quot; parent = &quot;pessoaService&quot; > < property name = &quot;cpf&quot; value = &quot;47888971210&quot; /> </ bean > </ beans >
  10. 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>
  11. 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, &quot;nome&quot; , &quot;nome.vazio&quot; ); Pessoa p = (Pessoa) target; if (p.getIdade() < 0) { errors.rejectValue( &quot;idade&quot; , &quot;valor negativo&quot; ); } else if (p.getIdade() > 120) { errors.rejectValue( &quot;idade&quot; , &quot;velho de mais&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; } }
  12. 14. <? 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; default-lazy-init = &quot;true&quot; > < bean id = &quot;pessoa&quot; class = &quot;com.targettrust.spring.validate.Pessoa&quot; > < property name = &quot;nome&quot; value = &quot;Fulano&quot; /> < property name = &quot;idade&quot; value = &quot;-1&quot; /> </ bean > </ beans >
  13. 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( &quot;/com/targettrust/spring/validate/Spring-beans.xml&quot; ); Pessoa p = (Pessoa) bf.getBean( &quot;pessoa&quot; ); System. out .println( &quot;Nome: &quot; + p.getNome() + &quot; idade: &quot; + p.getIdade()); Errors e = new BeanPropertyBindingResult(p, &quot;Pessoa&quot; ); p.validate(p, e); for (Object es: e.getAllErrors()){ System. out .println(es); } } } Chamada manual !!!
  14. 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>
  15. 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>
  16. 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>
  17. 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>
  18. 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( &quot;beans.xml&quot; )); MeuBeanPostProcessor postProcessor = new MeuBeanPostProcessor(); factory.addBeanPostProcessor(postProcessor);
  19. 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 { }
  20. 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( &quot;Craindo bean: &quot; + beanName); return bean; } }
  21. 24. <? 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; default-lazy-init = &quot;false&quot; > < bean id = &quot;a&quot; class = &quot;com.targettrust.spring.beanpostprocessors.ObjetoA&quot; /> < bean id = &quot;b&quot; class = &quot;com.targettrust.spring.beanpostprocessors.ObjetoB&quot; /> < bean id = &quot;c&quot; class = &quot;com.targettrust.spring.beanpostprocessors.ObjetoC&quot; /> < bean class = &quot;com.targettrust.spring.beanpostprocessors.LogCreationBeanPostProcessor” /> </ beans >
  22. 25. package com.targettrust.spring.beanpostprocessors; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Teste { public static void main(String[] args) { new ClassPathXmlApplicationContext( &quot;/com/targettrust/spring/&quot; + &quot;beanpostprocessors/Spring-beans.xml&quot; ); } }
  23. 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>
  24. 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>
  25. 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()); } }
  26. 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( &quot;./src/com/targettrust/spring/” + beanfactorypostprocessors/patterns.properties&quot; )); System. out .println( &quot;Patterns: &quot; + p); } catch (Exception e) { throw new FatalBeanException( &quot;Erro ao buscar patterns!&quot; ,e); } Map<Object,Object> beans = beanFactory.getBeansOfType(DataService. class ); for (Entry<Object, Object> e: beans.entrySet()){ System. out .println( &quot;Aplicando pattern em service: &quot; + e); DataService service = ((DataService)e.getValue()); service.setPattern(p.getProperty( &quot;pattern.&quot; + service.getPattern().replace( &quot;#&quot; , &quot;&quot; ))); } } }
  27. 30. <? 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; default-lazy-init = &quot;false&quot; > < bean id = &quot;brasilDateService&quot; class = &quot;com.targettrust.spring.beanfactorypostprocessors.DataService&quot; > < property name = &quot;pattern&quot; value = &quot;#brasil&quot; /> </ bean > < bean id = &quot;usDateService&quot; class = &quot;com.targettrust.spring.beanfactorypostprocessors.DataService&quot; > < property name = &quot;pattern&quot; value = &quot;#us&quot; /> </ bean > < bean class = &quot;com.targettrust.spring.beanfactorypostprocessors.DatePatternRouterBeanFactoryPostProcessor&quot; /> </ beans >
  28. 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( &quot;/com/targettrust/spring/beanfactorypostprocessors/Spring-beans.xml&quot; ); System. out .println( &quot;Data Brasil pattern : &quot; + ((DataService)ap.getBean( &quot;brasilDateService&quot; )).showSysDate()); System. out .println( &quot;Data Us pattern : &quot; + (DataService)ap.getBean( &quot;usDateService&quot; )).showSysDate()); } }
  29. 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>< bean id = &quot;txt&quot; class = &quot;java.io.File&quot; > < constructor-arg index = &quot;0&quot; value = &quot;C:/BOOTSECT.BAK&quot; /> </ bean >
  30. 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>
  31. 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 ; } }
  32. 38. package com.targettrust.spring.propertyeditor; import java.util.List; public class Turma { private String nome ; private List<Aluno> alunos ; public Turma() {} public Turma(String nome, List<Aluno> alunos) { super (); this . nome = nome; this . alunos = alunos; } public String getNome() { return nome ; } public void setNome(String nome) { this . nome = nome; } public List<Aluno> getAlunos() { return alunos ; } public void setAlunos(List<Aluno> alunos) { this . alunos = alunos; } @Override public String toString() { return nome + &quot; alunos: &quot; + alunos .toString(); } }
  33. 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); } }
  34. 40. <? 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;turma“ class = &quot;com.targettrust.spring.propertyeditor.Turma&quot; > < property name = &quot;nome&quot; value = &quot;Curso-Spring&quot; /> < property name = &quot;alunos&quot; > < list > < value > Rod </ value > < value > Joe </ value > < value > Bart </ value > < value > Homer </ value > < value > Hammer </ value > </ list > </ property > </ bean > < bean id = &quot;customEditorConfigurer“ class = &quot;org.springframework.beans.factory.config.CustomEditorConfigurer“ > < property name = &quot;customEditors&quot; > < map > < entry key = &quot;com.targettrust.spring.propertyeditor.Aluno&quot; > < bean class = &quot;com.targettrust.spring.propertyeditor.AlunoEditor&quot; /> </ entry > </ map > </ property > </ bean > </ beans >
  35. 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>
  36. 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 ; } }
  37. 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( &quot;Viva! Dia: &quot; + fe.getData() + &quot; é feriado. Uhhuu!!!&quot; ); } } }
  38. 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 , &quot;01/01/08&quot; )); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ac = applicationContext; } }
  39. 46. <? 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;rh&quot; class = &quot;com.targettrust.spring.event.RH&quot; /> < bean id = &quot;funcionarioEsperto &quot; class = &quot;com.targettrust.spring.event.FeriadoListener&quot; /> </ beans >
  40. 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( &quot;/com/targettrust/spring/event/Spring-beans.xml&quot; ); RH rh = (RH)ac.getBean( &quot;rh&quot; ); rh.pulicarFeriados(); } }
  41. 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>
  42. 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>
  43. 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
  44. 51. <? 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 class = &quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot; > < property name = &quot;location“ > < value > classpath:com/targettrust/spring/propertyplaceholderconfigurer/config.properties </ value > </ property > < property name = &quot;properties&quot; > < value > time=Grêmio </ value > </ property > </ bean > < bean id = &quot;I” class = &quot;com.targettrust.spring.propertyplaceholderconfigurer.Instrutor&quot; > < property name = &quot;nome&quot; value = &quot;${nome}&quot; /> < property name = &quot;idade&quot; value = &quot;${idade}&quot; /> < property name = &quot;time&quot; value = &quot;${time}&quot; /> < property name = &quot;altura&quot; value = &quot;${altura}&quot; /> </ bean > </ beans >
  45. 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>
  46. 53. package com.targettrust.spring.singletonbeanfactorylocator; public class ObjetoA {} <? 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; default-lazy-init = &quot;true&quot; > < bean id = &quot;A1&quot; class = &quot;com.targettrust.spring.singletonbeanfactorylocator.ObjetoA” /> </ beans > + A2 A3 A4
  47. 54. <? 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; default-lazy-init = &quot;false&quot; > < bean id = &quot;beanFactoryBean“ class = &quot;org.springframework.context.support.ClassPathXmlApplicationContext” > < constructor-arg > < list > < value > com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-A.xml </ value > < value > com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-B.xml </ value > < value > com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-C.xml </ value > </ list > </ constructor-arg > </ bean > < bean id = &quot;beanFactoryBean2“ class = &quot;org.springframework.context.support.ClassPathXmlApplicationContext“ > < constructor-arg > < list > < value > com/targettrust/spring/singletonbeanfactorylocator/Spring-beans-D.xml </ value > </ list > </ constructor-arg > </ bean > </ beans >
  48. 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( &quot;beanFactoryBean&quot; ); ObjetoA a1 = (ObjetoA)bf.getFactory().getBean( &quot;A1&quot; ); ObjetoA a2 = (ObjetoA)bf.getFactory().getBean( &quot;A2&quot; ); ObjetoA a3 = (ObjetoA)bf.getFactory().getBean( &quot;A3&quot; ); bf = bfl.useBeanFactory( &quot;beanFactoryBean2&quot; ); ObjetoA a4 = (ObjetoA)bf.getFactory().getBean( &quot;A4&quot; ); System. out .println( &quot;ObjetoA a1: &quot; + a1); System. out .println( &quot;ObjetoA a2: &quot; + a2); System. out .println( &quot;ObjetoA a3: &quot; + a3); System. out .println( &quot;ObjetoA a4: &quot; + a4); } }
  49. 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>
  50. 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<=0 || idade >= 120 ) throw new IllegalArgumentException( ms .getMessage( &quot;idade.invalida&quot; , new Object[]{idade},Locale. getDefault ())); this . idade = idade; } }
  51. 58. idade.invalida= A idade: {0} não é aceitável por que é muito velha ou menor do que 1 <? 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;messageSource“ class = &quot;org.springframework.context.support.ResourceBundleMessageSource“ > < property name = &quot;basenames&quot; > < list > < value > mensagems </ value > </ list > </ property > </ bean > < bean id = &quot;pessoa“ class = &quot;com.targettrust.spring.i18n.Pessoa“ /> </ beans >
  52. 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( &quot;/com/targettrust/spring/i18n/Spring-beans.xml&quot; ); Locale. setDefault ( new Locale( &quot;pt&quot; , &quot;BR&quot; )); setIdade (ac); } private static void setIdade(ApplicationContext ac){ Pessoa p = (Pessoa)ac.getBean( &quot;pessoa&quot; ); p.setNome( &quot;Crom&quot; ); try { p.setIdade(200); } catch (RuntimeException re){ re.printStackTrace(); } } }
  53. 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>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×