<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Simples</title>
	<atom:link href="http://www.javasimples.com.br/feed" rel="self" type="application/rss+xml" />
	<link>http://www.javasimples.com.br</link>
	<description>Porque Java não precisa ser difícil...</description>
	<lastBuildDate>Mon, 07 May 2012 00:36:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Minicurso sobre Spring na Infoeste 2012</title>
		<link>http://www.javasimples.com.br/outras/minicurso-sobre-spring-na-infoeste-2012</link>
		<comments>http://www.javasimples.com.br/outras/minicurso-sobre-spring-na-infoeste-2012#comments</comments>
		<pubDate>Mon, 07 May 2012 00:34:52 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Outras]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[curso]]></category>
		<category><![CDATA[dependencia]]></category>
		<category><![CDATA[fipp]]></category>
		<category><![CDATA[infoeste]]></category>
		<category><![CDATA[injecao]]></category>
		<category><![CDATA[minicurso]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[roo]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=695</guid>
		<description><![CDATA[Tá chegando a INFOESTE 2012 pessoal! A faculdade na qual eu me formei (FIPP) anualmente promove a INFOESTE, um evento com a duração de uma semana composto por diversas atrações relacionadas a tecnologia e informática como: maratona de programação, palestras e mesas redondas, vários minicursos, competição de web design, festa de instalação linux entre outros. [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/barra-fipp.jpg"><img class="aligncenter  wp-image-696" title="barra-fipp" src="http://www.javasimples.com.br/wp-content/uploads/barra-fipp.jpg" alt="" width="532" height="104" /></a></p>
<p style="text-align: left;">Tá chegando a <a title="INFOESTE 2012" href="http://www.unoeste.br/fipp/infoeste/24info/default.asp" target="_blank">INFOESTE 2012</a> pessoal! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p style="text-align: left;">A faculdade na qual eu me formei (<a title="Faculdade de Informática de Presidente Prudente" href="http://www.unoeste.br/fipp/" target="_blank">FIPP</a>) anualmente promove a INFOESTE, um evento com a duração de uma semana composto por diversas atrações relacionadas a tecnologia e informática como: maratona de programação, palestras e mesas redondas, vários minicursos, competição de web design, festa de instalação linux entre outros.</p>
<p style="text-align: left;">Este ano estarei ministrando o minicurso <strong>Introdução ao Spring Framework</strong> nos dias 17 e 18/05.</p>
<p style="text-align: left;">Quem participar vai ter uma pequena introdução sobre o tal do Spring, porque foi criado, como funciona a injeção de dependência e alguns frameworks da família Spring.</p>
<p style="text-align: left;">Começaremos aprendendo o mais básico e mais poderoso, a injeção de dependência, como ela era no princípio (através de XMLs), como evoluiu (@<em>Autowired</em>) e como está hoje (@<em>Value</em>, @<em>Configuration</em>, &#8230;).</p>
<p style="text-align: left;">Depois iremos desenvolver o QuizMVC, um quiz web utilizando <strong>Spring MVC</strong> e <strong>Spring Security</strong>. Desenvolveremos a aplicação completa, desde o CRUD de perguntas do quiz até o controle de acesso através de usuários persistidos em um banco de dados.</p>
<p style="text-align: left;">Por fim veremos como utilizar o <strong>Spring Roo</strong> (aposto que todo mundo vai adorar! hehehe) e &#8211; dependendo do tempo &#8211; iremos dar uma passadinha por cima de alguns outros frameworks como <strong>Spring BlazeDS Integration</strong> e <strong>Spring for Android</strong>.</p>
<p style="text-align: left;">Quem participar vai sair conhecendo pelo menos um pouco por cima o que é o Spring e como desenvolver uma aplicação web utilizando as facilidades que ele provê.</p>
<p style="text-align: left;">Abraços e até a infoeste então pessoal!</p>
<p style="text-align: left;">Saab.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/outras/minicurso-sobre-spring-na-infoeste-2012/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring Framework Parte 7 -&gt; Agendamento de Tarefas</title>
		<link>http://www.javasimples.com.br/spring-2/spring-framework-parte-7-agendamento-de-tarefas</link>
		<comments>http://www.javasimples.com.br/spring-2/spring-framework-parte-7-agendamento-de-tarefas#comments</comments>
		<pubDate>Tue, 28 Feb 2012 21:20:48 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[agendamento]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[quartz]]></category>
		<category><![CDATA[scheduled]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=622</guid>
		<description><![CDATA[Algo um tanto quanto comum em aplicações de médio / grande porte é o agendamento de tarefas. Exemplos: toda madrugada atualizar alguns registros que dependam de data (ex: contratos atrasados), todos os dias às 20:00h enviar e-mail para os clientes que façam aniversários no dia, todo domingo das 18:00h até  23:59h atualizar o data warehouse [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.javasimples.com.br/wp-content/uploads/agendamento.jpg" target="_blank"><img class="size-full wp-image-651 alignright" title="agendamento" src="http://www.javasimples.com.br/wp-content/uploads/agendamento.jpg" alt="" width="283" height="286" /></a></p>
<p style="text-align: left;">Algo um tanto quanto comum em aplicações de médio / grande porte é o agendamento de tarefas.</p>
<p style="text-align: left;">Exemplos: toda madrugada atualizar alguns registros que dependam de data (ex: contratos atrasados), todos os dias às 20:00h enviar e-mail para os clientes que façam aniversários no dia, todo domingo das 18:00h até  23:59h atualizar o data warehouse (DW) da empresa com as vendas da semana.</p>
<p style="text-align: left;">Surgem muitas e muitas idéias e possibilidades quando pensamos no agendamento de tarefas. Legal, na visão do cliente e do seu gerente é uma grande maravilha (de fato, realmente é) mas ai chega um requisito na tua mesa te falando pra <strong>magicamente</strong> <strong>fazer isso &#8220;pra ontem&#8221;</strong>.</p>
<p style="text-align: left;">E agora? Agora o Java Simples está aqui pra te ajudar! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p style="text-align: left;">Vamos criar um projeto utilizando o agendamento de tarefas provido pelo Spring pois é simples de usar e poderoso o suficiente para resolver a maioria das necessidades quando o assunto é agendamento.</p>
<p style="text-align: left;">Por que não utilizar o <a title="Quartz Scheduler" href="http://quartz-scheduler.org/" target="_blank">Quartz</a>?</p>
<p>Pois  é uma ferramenta incrivelmente robusta que provê funcionalidades como suporte para clusterização e transações JTA. Na boa, na maioria dos casos o Quartz é um ferrari pra comprar pão na esquina &#8211; como dizia uma professora que tive.</p>
<p style="text-align: left;">Vamos manter as coisas simples até que seja realmente necessário complicá-las!</p>
<p style="text-align: left;">* Mas eu confesso, a imagem do post é do site do Quartz&#8230; hehehe <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p style="text-align: left;"><span id="more-622"></span></p>
<h1 style="text-align: left;">Nossa aplicação</h1>
<p>Vamos imaginar que você trabalha em uma startup na área de desenvolvimento de software e o seu chefe te escolheu para criar uma pequena aplicação para ele poder ter mais controle sobre a empresa.</p>
<p>Nessa empresa é utilizado o Scrum como processo de desenvolvimento. Sempre antes de ir embora os desenvolvedores acessam o sistema de controle da empresa para marcar quais atividades estão concluídas, quais estão em andamento e quais ainda estão paradas.</p>
<p>Existem algumas máquinas que o chefe gosta de chamar de servidores (dá um desconto vai, está no começo ainda) pois elas executam os papéis de servidores de firewall, banco de dados (onde roda o mysql) e de aplicações (onde roda o tomcat).</p>
<p>O chefe quer chegar todo dia de manhã e a primeira coisa que ele quer fazer é verificar um e-mail enviado pelo novo sistema com o andamento das tarefas do dia anterior, inclusive, ele quer que no e-mail apareça em vermelho o nome das pessoas que não atualizaram o status das tarefas no dia anterior pra ele poder ter uma &#8220;conversinha&#8221; com elas. hehehehe</p>
<p>Outra coisa que acontece bastante na empresa é que os servidores costumar cair. Sempre que isso acontece você pensa: &#8220;Eu já disse que aquelas máquina não são servidores! Viu só! Não aguentam a carga!&#8221;.</p>
<p>Tudo bem, todos concordamos que essa situação não é muito legal mas até a empresa arranjar mais alguns clientes o chefe disse que não vai trocar nada. Por causa dessas quedas frequentes ele também quer que toda vez que algum servidor pare de funcionar ele receba um email avisando isso.</p>
<p>Uma última necessidade é que a aplicação seja web e seja possível o chefe saber qual servidor parou, quando o e-mail foi enviado, enfim, um histórico de tudo que o seu programa fez. Ele quer isso para que ele possa verificar tudo através do celular.</p>
<p>Recapitulando então, a aplicação vai ser web, vai ter que enviar um e-mail bem cedo com o andamento das tarefas do dia anterior e  toda vez que algum servidor cair ele quer receber um e-mail informando.</p>
<p>Legal, agora que já temos o nosso escopo vamos ao trabalho!</p>
<h2>O projeto</h2>
<p>No fim desse post teremos um projeto com essa estrutura:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/hierarquia-pacotes1.png" target="_blank"><img class="aligncenter size-full wp-image-655" title="hierarquia pacotes" src="http://www.javasimples.com.br/wp-content/uploads/hierarquia-pacotes1.png" alt="" width="391" height="600" /></a></p>
<p>Após o projeto web ter sido criado e todas as dependências corretamente referenciadas vamos dar uma olhada no web.xml:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;web-app</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;3.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>WEB-INF/applicationContext.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/context-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.context.ContextLoaderListener<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;welcome-file-list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>index.jsp<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/welcome-file-list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/web-app<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Apenas informamos o listener para carregar o Spring assim que a aplicação for iniciada e definimos o arquivo para ser compatível com servlets 3.0 .</p>
<p>O arquivo de configuração do Spring também não tem nenhum segredo:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span> <span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:task</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/task&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.agendamento&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;task:annotation-driven</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Através da tag <em>&lt;context:component-scan&gt;</em> o Spring vai procurar sozinho pelos beans que ele deve gerenciar<em> </em>(como explicado no post <a title="Spring Framework Parte 6 -&gt; Injeção de Dependência via Anotações" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-6-injecao-de-dependencia-via-anotacoes">Injeção de dependências via anotações</a>).</p>
<p>E através da tag <em>&lt;task:annotation-driven /&gt;</em> o Spring também vai procurar automaticamente por tarefas agendadas e vai ficar responsável pela execução delas.</p>
<h2>A interface Web</h2>
<p>Nossa aplicação web vai usar uma estrutura bem simples (servlet + JSP) apenas para não alongar muito o post.</p>
<p>A única página que vamos desenvolver vai mostrar um histórico de tudo que a aplicação já fez, vamos ver como ficaria a página <em>index.jsp</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
	pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
&lt;title&gt;Tarefas Agendadas&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;p&gt;
		&lt;a href=&quot;./historico&quot;&gt;Recarregar...&lt;/a&gt;
	&lt;/p&gt;
	&lt;p&gt;Tarefas executadas:&lt;/p&gt;
&nbsp;
	&lt;c:if test=&quot;${historico != null &amp;&amp; historico.size() &gt; 0}&quot;&gt;
		&lt;ul&gt;
			&lt;c:forEach var=&quot;hist&quot; items=&quot;${historico}&quot;&gt;
				&lt;li&gt;${hist}&lt;/li&gt;
			&lt;/c:forEach&gt;
		&lt;/ul&gt;
	&lt;/c:if&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Um simples JSP que vai mostrar todos os registros de um histórico que um servlet irá retornar. Vamos dar uma conferida no servlet:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Servlet para a recuperação do histórico de todas as tarefas executadas.
 *
 * @author Felipe
 */</span>
@WebServlet<span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;/historico&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HistoricoServlet <span style="color: #000000; font-weight: bold;">extends</span> HttpServlet <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>3612078136798710447L<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> HistoricoExecucao historicoExecucao<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span>ServletConfig config<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> ServletException <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>config<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		SpringBeanAutowiringSupport.<span style="color: #006633;">processInjectionBasedOnServletContext</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, config.<span style="color: #006633;">getServletContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> doGet<span style="color: #009900;">&#40;</span>HttpServletRequest req, HttpServletResponse resp<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> ServletException, <span style="color: #003399;">IOException</span> <span style="color: #009900;">&#123;</span>
		req.<span style="color: #006633;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;historico&quot;</span>, historicoExecucao.<span style="color: #006633;">getHistorico</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		RequestDispatcher dispatcher <span style="color: #339933;">=</span> req.<span style="color: #006633;">getRequestDispatcher</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;index.jsp&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		dispatcher.<span style="color: #006633;">forward</span><span style="color: #009900;">&#40;</span>req, resp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Toda vez que chegar uma requisição GET na URL <em>/historico</em> da nossa aplicação o servlet vai carregar o histórico através do bean <em>historicoExecucao</em> e vai renderizar a página <em>index.jsp</em> para o usuário saber quais foram as últimas tarefas executadas.</p>
<p>Por que a sobrescrita do método <em>init(ServletConfig)</em>?</p>
<p>Bom&#8230; nosso servlet possui um atributo que precisa ser injetado pelo Spring; o Spring só consegue injetar dependências em beans que estão sendo gerenciador por ele, ou seja, os beans devem estar no contexto do Spring para terem suas dependências injetadas; em tempo de execução quem vai instanciar o servlet é o container web (ex: tomcat) e não o Spring;</p>
<p>Sendo assim, quando o servlet é instanciado ele não está no contexto do Spring e consequentemente não terá suas dependências injetadas. Para ter as suas dependências injetadas nós invocamos o método estático  <em>processInjectionBasedOnServletContext(Object, ServletContext)</em> da classe <em>SpringBeanAutowiringSupport</em> para o Spring fazer esse favor para nós. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Vamos ver então o que esse <em>historicoExecucao</em> faz:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que contém o histórico de execução de todas as tarefas.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HistoricoExecucao <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">List</span> historico<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">SimpleDateFormat</span> simpleDateFormat<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> HistoricoExecucao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		historico <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ArrayList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		simpleDateFormat <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">SimpleDateFormat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;dd/MM/yyyy - HH:mm:ss&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> novoHistorico<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> hist<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		historico.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>simpleDateFormat.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;: &quot;</span> <span style="color: #339933;">+</span> hist<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">List</span> getHistorico<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> historico<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>É uma classe que simplesmente mantém um histórico de mensagens em memória. Vamos utilizar ela para manter um histórico de todas as tarefas que foram executadas pela nossa aplicação.</p>
<h2>Agendamento de tarefas</h2>
<p>Uma vez que o servlet está pronto vamos começar a agendar as tarefas.</p>
<p>Vamos começar com a classe responsável por verificar o status dos servidores.</p>
<p>Tudo o que vamos fazer é realizar um ping nos servidores para verificar se eles estão online. Como você é um desenvolvedor esperto você pensou: &#8220;Bom.. pode ser que em um outro momento seja necessário utilizar a funcionalidade de dar <em>ping</em> em alguma máquina ou até mesmo recuperar os IPs dos servidores&#8230; Já sei! Vou colocar em uma classe utilitária!&#8221;</p>
<p>Boa! E com isso temos a classe <em>InfraUtils</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe utilitária para tarefas relacionadas a infra estrutura.
 *
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> InfraUtils <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> IP_SERVIDOR_FIREWALL <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;192.168.0.20&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> IP_SERVIDOR_BD <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;192.168.0.21&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> IP_SERVIDOR_APLICACAO <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;192.168.0.22&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> IPS_SERVIDORES <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>IP_SERVIDOR_FIREWALL, IP_SERVIDOR_BD, IP_SERVIDOR_APLICACAO<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> 
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">boolean</span> pingaServidor<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> ip<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Simula o ping</span>
		<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">Thread</span>.<span style="color: #006633;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3500</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">Thread</span>.<span style="color: #006633;">currentThread</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">interrupt</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Verifica o resultado do ping</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Math</span>.<span style="color: #006633;">random</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Agora que já temos a estrutura para realizar um ping &#8211; ou pelo menos simular um &#8211; vamos para as tarefas mesmo. Vamos começar criando uma interface para padronizar todas as nossas tarefas:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Contrato que define os métodos necessários para uma tarefa.
 *
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Tarefa <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A única coisa que uma <em>Tarefa</em> vai ter que fazer é ser executada. Simples assim. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Agora que já sabemos como vai ser uma tarefa podemos criar a <em>TarefaPingServidores</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Tarefa para pingar os servidores e verificar se estão ativos ou não.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefaPingServidores <span style="color: #000000; font-weight: bold;">implements</span> Tarefa <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> HistoricoExecucao historicoExecucao<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>args <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">||</span> args.<span style="color: #006633;">length</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A tarefa deve receber o IP do servidor a ser pingado!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #003399;">String</span> ipServidor <span style="color: #339933;">=</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> nomeServidor <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Servidor de &quot;</span> <span style="color: #339933;">+</span> InfraUtils.<span style="color: #006633;">traduzirIp</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> historico <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>InfraUtils.<span style="color: #006633;">pingaServidor</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; pingado com sucesso.&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; caiu!&quot;</span><span style="color: #339933;">;</span>
			EmailUtils.<span style="color: #006633;">enviaEmail</span><span style="color: #009900;">&#40;</span>EmailUtils.<span style="color: #006633;">EMAIL_CHEFE</span>, historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		historicoExecucao.<span style="color: #006633;">novoHistorico</span><span style="color: #009900;">&#40;</span>historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Nossa tarefa segue uma lógica um tanto quanto simples não? Garante que foi enviado o IP do servidor a ser pingado, pega o nome do servidor a partir do seu IP, se não pingou com sucesso, ou seja, se o servidor caiu envia um e-mail para o chefe e por fim registra o que aconteceu no histórico.</p>
<p>Como envia o e-mail? Sinto muito mas não vai ser hoje que vamos ver&#8230; hehehehe</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe utilitária para o envio de emails.
 *
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> EmailUtils <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> EMAIL_CHEFE <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;chefe@empresa.com.br&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> enviaEmail<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> para, <span style="color: #003399;">String</span> mensagem<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Email enviado para %s com a mensagem <span style="color: #000099; font-weight: bold;">\&quot;</span>%s<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>,
							para,
							mensagem<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>A anotação @<em>Scheduled</em></h3>
<p>Ok, temos a nossa primeira tarefa pronta. Mas como vamos fazer ela ser executada a cada 5 segundos?</p>
<p>Vamos dar uma olhada na classe <em>TarefasAgendadas</em> que é onde vão ficar todas os nossos agendamentos para a execução de tarefas:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que contém todas as tarefas agendadas do sistema.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefasAgendadas <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;tarefaPingServidores&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Tarefa pingarServidores<span style="color: #339933;">;</span>
&nbsp;
	@Scheduled<span style="color: #009900;">&#40;</span>fixedDelay<span style="color: #339933;">=</span><span style="color: #cc66cc;">5000</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> pingarServidores<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> servidores <span style="color: #339933;">=</span> InfraUtils.<span style="color: #006633;">IPS_SERVIDORES</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> servidores.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			pingarServidores.<span style="color: #006633;">executar</span><span style="color: #009900;">&#40;</span>servidores<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A primeira coisa que precisamos prestar atenção é a classe está anotada com <em>@Component</em>, ou seja, ela será um bean que o Spring vai descobrir automaticamente. Uma vez que o Spring está gerenciando esse bean e encontra a anotação @<em>Scheduled</em> ele já prepara toda a infra estrutura necessária para realizar essa tarefa de acordo com o agendamento informado na anotação.</p>
<p>A anotação @<em>Scheduled</em> possui 3 parâmetros para podermos definir o agendamento das tarefas: <em>fixedDelay</em>, <em>fixedRate</em> e <em>cron</em>.</p>
<ul>
<li><strong><em>fixedDelay</em></strong> é um valor em milissegundos que será esperado entre o fim de uma execução e o começo de outra;</li>
<li><strong><em>fixedRate</em></strong> é um valor em milissegundos que será esperado entre as invocações, ou seja, sem considerar o fim do método;</li>
<li><strong><em>cron</em></strong> é uma String contendo uma CronExpression. Veremos detalhes mais a seguir.</li>
</ul>
<p>Para o método pingarServidores<em>()</em> nós definimos que a cada 5 segundos desde sua última execução ele deverá ser invocado novamente. Com isso basta executarmos a aplicação, esperar alguns segundos, clicar no link <em>Recarregar e</em> teremos uma saída parecida com essa:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/saida-ping-servidor.png" target="_blank"><img class="aligncenter size-full wp-image-657" title="saida ping servidor" src="http://www.javasimples.com.br/wp-content/uploads/saida-ping-servidor.png" alt="" width="523" height="212" /></a></p>
<h3>A anotação @<em>Async</em></h3>
<p>Depois que você diz para o teu chefe que terminou a funcionalidade de pingar os servidores ele pergunta: &#8220;Mas o ping nos servidores está sendo feito de forma assíncrona certo?&#8221;. Errado! Do jeito que está as chamadas estão sendo feitas de maneira síncrona dentro do <em>for</em>, ou seja, para pingar o segundo servidor tem que esperar o ping do primeiro terminar e assim por diante.</p>
<p>Mas por sorte a galera do Spring já pensou nisso e já disponibilizou uma anotação para resolver o nosso problema: a anotação @<em>Async</em>.</p>
<p>Para tornarmos os pings assíncronos basta fazermos o seguinte:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe responsável pelas tarefas agendadas relacionadas a infra estrutura.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefaPingServidores <span style="color: #000000; font-weight: bold;">implements</span> Tarefa <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> HistoricoExecucao historicoExecucao<span style="color: #339933;">;</span>
&nbsp;
	@Async
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>args <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">||</span> args.<span style="color: #006633;">length</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A tarefa deve receber o IP do servidor a ser pingado!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #003399;">String</span> ipServidor <span style="color: #339933;">=</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> nomeServidor <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Servidor de &quot;</span> <span style="color: #339933;">+</span> InfraUtils.<span style="color: #006633;">traduzirIp</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> historico <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>InfraUtils.<span style="color: #006633;">pingaServidor</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; pingado com sucesso.&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; caiu!&quot;</span><span style="color: #339933;">;</span>
			EmailUtils.<span style="color: #006633;">enviaEmail</span><span style="color: #009900;">&#40;</span>EmailUtils.<span style="color: #006633;">EMAIL_CHEFE</span>, historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		historicoExecucao.<span style="color: #006633;">novoHistorico</span><span style="color: #009900;">&#40;</span>historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Só isso? Sim, só isso! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Para termos certeza de que isso vai funcionar mesmo vamos fazer o seguinte:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que contém todas as tarefas agendadas do sistema.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefasAgendadas <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;tarefaPingServidores&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Tarefa pingarServidores<span style="color: #339933;">;</span>
&nbsp;
	@Scheduled<span style="color: #009900;">&#40;</span>fixedDelay<span style="color: #339933;">=</span><span style="color: #cc66cc;">5000</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> pingarServidores<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> servidores <span style="color: #339933;">=</span> InfraUtils.<span style="color: #006633;">IPS_SERVIDORES</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> servidores.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			pingarServidores.<span style="color: #006633;">executar</span><span style="color: #009900;">&#40;</span>servidores<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>, i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe responsável pelas tarefas agendadas relacionadas a infra estrutura.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefaPingServidores <span style="color: #000000; font-weight: bold;">implements</span> Tarefa <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> HistoricoExecucao historicoExecucao<span style="color: #339933;">;</span>
&nbsp;
	@Async
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>args <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">||</span> args.<span style="color: #006633;">length</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A tarefa deve receber o IP do servidor a ser pingado!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;%s começando (%d)&quot;</span>,<span style="color: #003399;">Thread</span>.<span style="color: #006633;">currentThread</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">String</span> ipServidor <span style="color: #339933;">=</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> nomeServidor <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Servidor de &quot;</span> <span style="color: #339933;">+</span> InfraUtils.<span style="color: #006633;">traduzirIp</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">String</span> historico <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>InfraUtils.<span style="color: #006633;">pingaServidor</span><span style="color: #009900;">&#40;</span>ipServidor<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; pingado com sucesso.&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			historico <span style="color: #339933;">=</span> nomeServidor <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; caiu!&quot;</span><span style="color: #339933;">;</span>
			EmailUtils.<span style="color: #006633;">enviaEmail</span><span style="color: #009900;">&#40;</span>EmailUtils.<span style="color: #006633;">EMAIL_CHEFE</span>, historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		historicoExecucao.<span style="color: #006633;">novoHistorico</span><span style="color: #009900;">&#40;</span>historico<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;%s terminando (%d)&quot;</span>,<span style="color: #003399;">Thread</span>.<span style="color: #006633;">currentThread</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos enviar para a tarefa em qual loop ela foi executada (<em>pingarServidores.executar(servidores[i], i)</em>) e depois vamos logar o início e fim da execução de cada tarefa para podermos acompanhar se está acontecendo tudo em sequência mesmo ou se estão asíncronas.</p>
<p>Ao executar a aplicação e observar o console por algum tempo iremos ver o seguinte:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/execucao-assincrona.png" target="_blank"><img class="aligncenter  wp-image-658" title="execucao assincrona" src="http://www.javasimples.com.br/wp-content/uploads/execucao-assincrona.png" alt="" width="531" height="221" /></a></p>
<p>Só pelo nome da thread já podemos ver que funcionou né&#8230; Em adição ao nome, se repararmos na saída podemos ver que algumas invocações posteriores podem começar a ser executadas antes. Ex: 1, 0, 2 e 0, 2, 1.</p>
<p>Devido a anotação @<em>Async</em>, assim que o método for chamado ele já vai retornar e o Spring irá executá-lo em uma thread única, por isso vale lembrar que isso irá funcionar para métodos que não possuam retorno (<em>void)</em>. Caso seja necessário retornar um valor do método assíncrono devemos utilizar como retorno um objeto que implemente a interface <em>java.util.concurrent.Future</em>. Para mais informações consulte a <a title="Documentação Spring 3 (Scheduling)" href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#scheduling" target="_blank">documentação</a> e/ou o google. hehehe</p>
<p>Com isso terminamos o agendamento da tarefa para pingar os servidores da empresa! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Vamos para a nossa última tarefa: criar uma tarefa que envie um e-mail para o chefe todo dia com o andamento das sprints. Vamo primeiro criar a tarefa que fará isso:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe responsável pelo envio agendado de emails.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefaAndamentoDiarioSprints <span style="color: #000000; font-weight: bold;">implements</span> Tarefa <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> HistoricoExecucao historicoExecucao<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Levanta os dados necessários e monta a mensagem</span>
		<span style="color: #003399;">String</span> andamentoTarefas <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Segue o andamento das tarefas...&quot;</span><span style="color: #339933;">;</span>
		EmailUtils.<span style="color: #006633;">enviaEmail</span><span style="color: #009900;">&#40;</span>EmailUtils.<span style="color: #006633;">EMAIL_CHEFE</span>, andamentoTarefas<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		historicoExecucao.<span style="color: #006633;">novoHistorico</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Andamento das tarefas enviado por email.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Uma vez que temos a tarefa vamos agendá-la para que seja enviada no último segundo de cada dia, ou seja, 23:59:59h. Para isso usaremos o atributo <em>cron </em>da anotação @<em>Scheduled</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que contém todas as tarefas agendadas do sistema.
 *
 * @author Felipe
 */</span>
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TarefasAgendadas <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;tarefaPingServidores&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Tarefa pingarServidores<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;tarefaAndamentoDiarioSprints&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Tarefa andamentoDiarioSprints<span style="color: #339933;">;</span>
&nbsp;
	@Scheduled<span style="color: #009900;">&#40;</span>fixedDelay<span style="color: #339933;">=</span><span style="color: #cc66cc;">5000</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> pingarServidores<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> servidores <span style="color: #339933;">=</span> InfraUtils.<span style="color: #006633;">IPS_SERVIDORES</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> servidores.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			pingarServidores.<span style="color: #006633;">executar</span><span style="color: #009900;">&#40;</span>servidores<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>, i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Scheduled<span style="color: #009900;">&#40;</span>cron <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;59 59 23 ? * *&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> andamentoDiarioSprint<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		andamentoDiarioSprints.<span style="color: #006633;">executar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Expressões <em>cron</em></h3>
<p>O que são expressões cron afinal de contas (que string esquisita&#8230;)?</p>
<p><strong>cron</strong> é uma ferramenta UNIX muito poderosa para agendamento. Ela é utilizada há muito tempo, ou seja, sabemos que funciona! <strong>Expressões cron</strong> são as expressões que essa ferramenta utiliza para realizar os agendamentos. Tais expressões são formadas por 6 ou 7 campos separados por espaços em branco, representando períodos de tempo. Vamos dar uma olhada nesses campos:</p>
<table border="1">
<tbody>
<tr>
<th>Campo</th>
<th>Obrigatório?</th>
<th>Valores permitidos</th>
<th>Caracteres especiais permitidos</th>
</tr>
<tr>
<td>Segundos</td>
<td>Sim</td>
<td>0-59</td>
<td>* / , -</td>
</tr>
<tr>
<td>Minutos</td>
<td>Sim</td>
<td>0-59</td>
<td>* / , -</td>
</tr>
<tr>
<td>Horas</td>
<td>Sim</td>
<td>0-23</td>
<td>* / , -</td>
</tr>
<tr>
<td>Dia do mês</td>
<td>Sim</td>
<td>1-31</td>
<td>* / , - ? L W</td>
</tr>
<tr>
<td>Mês</td>
<td>Sim</td>
<td>1-12 ou JAN-DEC</td>
<td>* / , -</td>
</tr>
<tr>
<td>Dia da semana</td>
<td>Sim</td>
<td>0-6 ou SUN-SAT</td>
<td>* / , - ? L #</td>
</tr>
<tr>
<td>Ano</td>
<td>Não</td>
<td>1970–2099</td>
<td>* / , -</td>
</tr>
</tbody>
</table>
<p>Olhando para essa tabela agora já &#8211; quase &#8211; conseguimos ler a expressão que usamos na anotação @<em>Scheduled(cron =&#8221;59 59 23 ? * *&#8221;)</em>&#8230; Já sabemos que vai ser no horário 23:59:59, mas o que significam esses caracteres especiais? Vamos lá:</p>
<ul>
<li><strong>Asterísco (*)</strong> &#8211; utilizado para selecionar todos os valores. Ex: * no campo segundos significa &#8220;todos os segundos&#8221;;</li>
<li><strong>Interrogação (?)</strong> &#8211; utilizador quando o valor do campo não importa. Ex: quero que seja disparada uma tarefa todo dia 10 mas não me importo qual dia da semana vai ser o dia 10;</li>
<li><strong>Hífen (-)</strong> &#8211; utilizado para informar períodos. Ex: &#8220;1-4&#8243; no campo mês quer dizer que a tarefa será disparada em janeiro, fevereiro, março e abril;</li>
<li><strong>Vírgula (,)</strong> &#8211; utilizado para valores adicionais. Ex: &#8220;MON,WED,FRI&#8221; no campo dia da semana indica a execução na segunda, quarta e sexta feiras;</li>
<li><strong>Barra (/)</strong> &#8211; utilizado para especificar incrementos. Utiliza a seguinte sintaxe: &lt;início&gt;/&lt;incremento&gt; (se o início for omitido ele será interpretado como 0). Ex: &#8220;/30&#8243; no campo segundos significa &#8220;a cada 30 segundos&#8221; e &#8220;1/5&#8243; no campo dia do mês indica a execução nos dias &#8220;1, 6, 11, 16, &#8230;&#8221;;</li>
<li><strong>L (last)</strong> - possui alguns significados dependendo do campo em que é utilizado. Se for utilizado no campo dia do mês significa o último dia do mês, se for utilizado sozinho no campo dia da semana significa 7 ou SAT (sábado), se utilizado com algum valor no campo dia da semana seria &#8220;o último &#8230; do mês&#8221; (ex: &#8220;6L&#8221; seria &#8220;a última sexta feira do mês&#8221;), também é possível especificar um período antes do fim do mês no campo dia do mês (ex: &#8220;L-2&#8243; seria o antepenúltimo dia do mês);</li>
<li><strong>W (weekday)</strong> &#8211; usado para especificar o dia útil (segunda &#8211; sexta) mais próximo do dia informado. Ex: &#8220;15W&#8221; no campo dia do mês vai executar na segunda feira (dia 14) caso o dia 15 caia em um sábado ou então vai executar em uma segunda (16) caso o dia 15 seja um domingo. Se utilizarmos &#8220;1W&#8221; e o primeiro dia do mês seja um sábado, só vai executar na segunda feira (dia 3). Só é possível utilizar esse caractere quando o dia do mês for um único dia, sua utilização com períodos não é permitida;</li>
<li><strong>Sustenido (#)</strong> &#8211; utilizado para especificar o &#8220;n-ésimo&#8221; dia do mês. Ex: &#8220;6#3&#8243; no campo dia da semana significa &#8220;a terceira sexta feira do mês (6 = sexta, #3 = terceira)&#8221;; &#8220;4#5&#8243; significa &#8220;a quinta quarta feira do mês&#8221;, porém se não houver uma quinta quarta feira no mês a tarefa não será executada.</li>
</ul>
<div>Obs: Os caracteres <strong>L</strong> e <strong>W</strong> podem ser utilizados em conjunto no campo dia do mês. Ex: &#8220;LW&#8221; significa &#8220;o último dia útil do mês&#8221;.</div>
<p>Bom, expressões cron podem ser fáceis como &#8220;0 0 15 ? * *&#8221; ou podem ser complexas como &#8220;0/5 14,18,3-39,52 * ? JAN,MAR,SEP MON-FRI 2002-2010&#8243;.</p>
<p>Mas então&#8230; como saber se a sua expressão está certa ou não?</p>
<p>Para isso existe uma classe bem bacana na biblioteca do Quartz: <em>CronExpression.java</em>. Nela existe o método<em> getNextValidTimeAfter(Date)</em> que nos retorna a próxima data (a partir do parâmetro) na qual a tarefa será executada. Com isso nós podemos montar uma classe utilitária que nos permite testar se nossa expressão está certa ou não:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe responsável por realizar testes com as Cron Expressions.
 *
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TestaExpressao <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">SimpleDateFormat</span> sdf <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">SimpleDateFormat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;dd/MM/yyyy HH:mm:ss&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		mostrarProximasDatas<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;59 59 23 ? * *&quot;</span>, <span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> mostrarProximasDatas<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> cron, <span style="color: #000066; font-weight: bold;">int</span> quantDatas<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
			CronExpression e <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CronExpression<span style="color: #009900;">&#40;</span>cron<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #003399;">Date</span> ultimaData <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> quantDatas<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				ultimaData <span style="color: #339933;">=</span> e.<span style="color: #006633;">getNextValidTimeAfter</span><span style="color: #009900;">&#40;</span>ultimaData<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;%02d: %s&quot;</span>, i<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span>, sdf.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span>ultimaData<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Obs: para essa classe funcionar será necessário colocar a biblioteca do <a title="Download Quartz" href="http://quartz-scheduler.org/downloads/catalog" target="_blank">Quartz</a> no classpath.</p>
<p>O método <em>mostrarProximasDatas(String, int)</em> recebe uma expressão e a quantidade de datas futuras em que essa expressão irá disparar serão exibidas como parâmetros. Ao executar o exemplo acima vamos ter uma saída parecida com essa:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/saida-testa-expressao.png" target="_blank"><img class="aligncenter  wp-image-670" title="saida testa expressao" src="http://www.javasimples.com.br/wp-content/uploads/saida-testa-expressao.png" alt="" width="536" height="191" /></a></p>
<p style="text-align: left;">Vemos que vai disparar todo dia exatamente às 23:59:59, ou seja, conferimos que nossa expressão vai fazer exatamente o que queremos! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h1 style="text-align: left;">Conclusão</h1>
<p>Bom pessoal, depois desse pequeno post você vai conseguir entregar a aplicação para o seu chefe antes do prazo e ele vai ficar muito satisfeito com o resultado! hehehe</p>
<p>Mas sem brincadeiras, o Spring provê uma forma maneira muito fácil e ao mesmo tempo muito poderosa para agendarmos tarefas. Sem falar que incrivelmente legível né (devido ao uso de anotações e poucas configurações em XML).</p>
<p>Caso a sua aplicação seja muito grande mesmo e precise de tarefas agendadas como realizar transações bancárias (ou coisas de mesma importância) eu aconselharia dar uma olhada no Quartz mesmo. Ele provê algumas funcionalidades a nível de aplicações de grande porte como persistência dos jobs a serem executados (em caso de alguma falha), clusterização e suporte a transações JTA.</p>
<p>Caso queira o projeto basta realizar o download <a href="http://dl.dropbox.com/u/4918828/JavaSimples/spring.agendamento.rar" title="Download do projeto">aqui</a>.</p>
<p>Boa sorte com seus agendamentos! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>[]s e até o próximo,</p>
<p>Saab.</p>
<h1 style="text-align: left;">Links</h1>
<p style="text-align: left;">Seguem alguns links que me ajudaram e podem te ajudar também:</p>
<ul>
<li><a title="Obtaining Spring 3 Artifacts With Maven" href="http://blog.springsource.org/2009/12/02/obtaining-spring-3-artifacts-with-maven/" target="_blank">Obtendo as bibliotecas do Spring 3 pelo Maven</a></li>
<li><a title="Task Scheduling Simplifications in Spring 3.0" href="http://blog.springsource.org/2010/01/05/task-scheduling-simplifications-in-spring-3-0/" target="_blank">Simplificações em relação agendamento de tarefas no Spring 3</a></li>
<li><a title="Documentação do Spring 3" href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html" target="_blank">Documentação do Spring 3</a></li>
<li><a title="CronTrigger Tutorial" href="http://quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/crontrigger" target="_blank">CronTrigger Tutorial</a></li>
<li><a title="Download do Quartz" href="http://quartz-scheduler.org/downloads/catalog" target="_blank">Download do Quartz</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/spring-2/spring-framework-parte-7-agendamento-de-tarefas/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Spring 3.1 + Hibernate 4.0</title>
		<link>http://www.javasimples.com.br/hibernate-2/spring-3-1-hibernate-4-0</link>
		<comments>http://www.javasimples.com.br/hibernate-2/spring-3-1-hibernate-4-0#comments</comments>
		<pubDate>Wed, 22 Feb 2012 15:46:20 +0000</pubDate>
		<dc:creator>João Corrêa da Costa Junior</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[hibernate 4]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring 3]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=544</guid>
		<description><![CDATA[A idéia de criar este post foi do Felipe Saab quando sugeri a ele manter o post Spring Framework Parte 4 -&#62; Integração com o Hibernate atualizado para uma versão mais nova das bibliotecas. Porém essa atualização iria modificar uma parte da codificação do post então decidimos criar um novo focando somente em Spring 3.1 [...]]]></description>
			<content:encoded><![CDATA[<p>A idéia de criar este post foi do Felipe Saab quando sugeri a ele manter o post <a href="http://www.javasimples.com.br/?p=233">Spring Framework Parte 4 -&gt; Integração com o Hibernate</a> atualizado para uma versão mais nova das bibliotecas. </p>
<p>Porém essa atualização iria modificar uma parte da codificação do post então decidimos criar um novo focando somente em Spring 3.1 e Hibernate 4.0.</p>
<p>Aos que estão iniciando neste assunto, sugiro a leitura dos assuntos abordados em posts anteriores:</p>
<ul>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-1-dependency-injection/">Spring Framework Parte 1 -&gt; Dependency Injection</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-2-aspect-oriented-programming/">Spring Framework Parte 2 -&gt; Aspect Oriented Programming</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-3-java-database-connectivity-jdbc/">Spring Framework Parte 3 -&gt; Java Database Connectivity (JDBC)</a></li>
</ul>
<p>Neste tópico vamos abordar a configuração de um projeto utilizando Hibernate 4 com anotações (annotations), Spring 3.1 e uma base de dados MySQL.<span id="more-544"></span></p>
<h1><strong>Usar Annotations ou XML?</strong></h1>
<p>Existe muita discussão sobre este assunto. O Hibernate permite as duas formas, ambas tem suas vantagens e desvantagens.</p>
<p>Na minha opnião o Annotations tem grande vantagem pois elimina arquivos para cada mapeamento, aumenta a produtividade pela configuração ficar diretamente no POJO, ou seja, na classe java que representa a tabela que está sendo mapeada.</p>
<p>Uma das maneiras mais diretas de interagir com banco de dados usando o Java é via JDBC, porém exige muita codificação para manter os dados persistentes no sistema. Atualmente temos ferramentas como o Hibernate que nos auxiliam neste trabalho e que está evoluindo constantemente para ficar ainda melhor.</p>
<p>Bom, chega de papo, vamos codificar!</p>
<p>Vamos criar no Eclipse um novo Java Project chamado <strong>Spring_HibernateAnnotations</strong>.</p>
<p style="text-align: center;"><img class="size-medium wp-image-545 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img1-222x300.png" alt="Criar projeto java" width="222" height="300" /></p>
<h1>Bibliotecas e Dependências</h1>
<p>Criarei no projeto uma pasta lib e colocarei dentro as bibliotecas necessárias para rodar o Spring 3.1 e o Hibernate 4.0. As bibliotecas podem ser encontradas em:</p>
<ul>
<li><strong>Spring:</strong> <a href="http://www.springsource.org/download">http://www.springsource.org/download</a> (todos os arquivos da pasta dist)</li>
<li><strong>Hibernate:</strong> <a href="http://sourceforge.net/projects/hibernate/files/hibernate4/">http://sourceforge.net/projects/hibernate/files/hibernate4/</a> (todos os arquivos da pasta <strong>lib/required</strong> <strong>e lib/jpa</strong>)</li>
</ul>
<p>O Spring e o Hibernate fazem uso de bibliotecas auxiliares que precisarão ser adicionadas:</p>
<ul>
<li><strong>Commons Logging</strong>: <a href="http://commons.apache.org/logging/">http://commons.apache.org/logging/</a> (extraia e adicione somente o <strong>commons-logging-1.1.1</strong>.<strong>jar</strong>)</li>
<li><strong>SLF4J</strong>: <a href="http://www.slf4j.org/download.html">http://www.slf4j.org/download.html</a> (adicione somente <strong>slf4j-api-1.6.x.jar</strong> e <strong>slf4j-simple-1.6.x.jar</strong>)</li>
<li><strong>JTA</strong>: <a href="http://repo2.maven.org/maven2/javax/transaction/jta/1.1/">http://repo2.maven.org/maven2/javax/transaction/jta/1.1/</a> (adicione somente <strong>jta-1.1.jar</strong>)</li>
<li><strong>AspectJ</strong> <a href="http://www.eclipse.org/aspectj/downloads.php">http://www.eclipse.org/aspectj/downloads.php</a> (Extraia o <strong>aspectj-1.x.x .jar</strong> com o Winrar e adicione em seu projeto os arquivos da pasta lib)</li>
<li><strong>AOPAlliance</strong> <a href="http://aopalliance.sourceforge.net/">http://aopalliance.sourceforge.net/</a> (Adicione o <strong>aopalliance.jar</strong>)</li>
</ul>
<p>Para conectar com a base de dados MySQL precisamos também do conector:</p>
<ul>
<li><strong>Connector J</strong>: <a href="http://dev.mysql.com/downloads/connector/j/">http://dev.mysql.com/downloads/connector/j/</a> (Adicione o <strong>mysql-connector-java-x.x.x-bin.jar</strong>)</li>
</ul>
<p>Após adicionar os jars ao projeto devemos ter uma tela parecida com essa:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/img2.png" target="_blank"><img class=" wp-image-546 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img2.png" alt="Bibliotecas do Spring, Hibernate, JDBC, AspectJ" width="241" height="469" /></a></p>
<h1>Mãos à obra</h1>
<p>Vamos definir uma estrutura inicial de pacotes para o nosso projeto:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/img31.png" target="_blank"><img class="size-full wp-image-548 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img31.png" alt="Packages do Projeto" width="285" height="122" /></a></p>
<p>&nbsp;</p>
<ul>
<li><strong>conf</strong>: Guardará o arquivo de configurações</li>
<li><strong>spring_hibernateannotations</strong>:  Local onde ficarão as classes que farão execução</li>
<li><strong>spring_hibernateannotations.interfaces</strong>: Guardará as interfaces</li>
<li><strong>spring_hibernateannotations.modelo</strong>: Guardará os POJOs</li>
</ul>
<h2><strong>Arquivo de configuração</strong></h2>
<p>Vamos criar o arquivo de configuração do Spring com o nome <em>conf.xml</em> no pacote <em>conf</em>:</p>
<div>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;driverClassName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;com.mysql.jdbc.Driver&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;jdbc:mysql://localhost/hibernate_teste&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;username&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;root&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;root&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate4.LocalSessionFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;annotatedClasses&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>spring_hibernateannotations.modelo.Livro<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;hibernateProperties&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.dialect&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>org.hibernate.dialect.MySQLDialect<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.show_sql&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;banco_dados&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;spring_hibernateannotations.BancoDados&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<ul>
<li><strong>dataSource</strong>: Bean base para o acesso à base de dados. Injetamos nele as informações necessárias para realizar a conexão.</li>
<li><strong>sessionFactory</strong>: a <em>SessionFactory</em> é a parte do Hibernate responsável por carregar todo o mapeamento das nossas classes em memória e garantir que ele esteja correto. Informamos através da lista a<em>nnotatedClasses que a classe </em><em>spring_hibernateannotations.modelo.Livro</em> é uma classe anotada, ou seja, ela possui mapeamento realizado através de anotações. Com isso a sessionFactory vai validar (em tempo de execução) se as anotações que informamos na classe livro estão condizentes com o banco de dados e garantir que os dados das nossas classes sejam persistidos na base.</li>
<li><strong>banco_dados</strong>: Bean da nossa aplicação que irá encapsular toda a lógica de acesso aos dados. Injetamos a sessionFactory para nossa classe poder delegar tais acesso para ela.</li>
</ul>
<h2>Banco de Dados</h2>
<p>Vamos neste post seguir a estrutura de banco do <a title="Spring Framework Parte 4 -&gt; Integração com o Hibernate" href="http://www.javasimples.com.br/hibernate-2/spring-framework-parte-4-integracao-com-o-hibernate" target="_blank">post anterior</a>, ou seja, vamos utilizar a classe <em>Livro</em> e a tabela <em>Livros</em>.</p>
<p>Segue o script para criar a tabela no MySQL (conforme publicação anterior do Felipe Saab):</p>
<div>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span>  <span style="color: #ff0000;">'Livros'</span> <span style="color: #66cc66;">&#40;</span>
    <span style="color: #ff0000;">'liv_cod'</span> <span style="color: #993333; font-weight: bold;">INT</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #66cc66;">,</span>
    <span style="color: #ff0000;">'liv_titulo'</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">100</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">CHARACTER</span> <span style="color: #993333; font-weight: bold;">SET</span> utf8 <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #66cc66;">,</span>
    <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span>  <span style="color: #ff0000;">'liv_cod'</span> <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE <span style="color: #66cc66;">=</span> INNODB <span style="color: #993333; font-weight: bold;">CHARACTER</span> <span style="color: #993333; font-weight: bold;">SET</span> utf8 <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci;</pre></div></div>

</div>
<p>Segue a imagem da minha base de dados recentemente criada:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/img4.png" target="_blank"><img class="size-full wp-image-549 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img4.png" alt="Base utilizada para exemplo de código Spring + Hibernate + Annotation" width="177" height="203" /></a></p>
<p>Na package <strong>spring_hibernateannotations.modelo </strong>criarei a classe Livro.java com a seguinte estrutura:</p>
<div>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;livros&quot;</span><span style="color: #009900;">&#41;</span>
@GenericGenerator<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;mygenLivros&quot;</span>, strategy <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;increment&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Livro <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Serializable</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 6216997659936884192L<span style="color: #339933;">;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>generator <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;mygenLivros&quot;</span><span style="color: #009900;">&#41;</span>
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;liv_cod&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> cod<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;liv_titulo&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> titulo<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Getters e Setters</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Se vocês repararem bem, é uma simples classe com getters e setters, porém com algumas coisas a mais:</p>
<p><strong>implements Serializable</strong>: Uma boa prática é fazer com que todas as entidades mapeadas (@Entity) implementem a interface java.io.Serializable pois em quase todas as aplicações web as entidades são serializadas do servidor para o cliente. Essa implementação garante que nenhum dado se perca durante a serialização.</p>
<p><strong>Campo estático serialVersionUID</strong>: A serialização necessita de um identificador da classe (mais detalhes em <a href="http://blog.caelum.com.br/entendendo-o-serialversionuid/">http://blog.caelum.com.br/entendendo-o-serialversionuid/</a>). Uma possibilidade é gerá-lo utilizando o próprio eclipse:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/img5.png" target="_blank"><img class=" wp-image-550 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img5.png" alt="Geração de Serial Version ID pelo Eclipse" width="510" height="178" /></a></p>
<h2><strong>Hibernate Annotations</strong></h2>
<p>Caso você não saiba o que são anotações aconselho a leitura do post <a title="Annotations: O que é, pra que serve?" href="http://www.javasimples.com.br/?p=136" target="_blank">Annotations: O que é, pra que serve?</a>.</p>
<p>São as informações (metadados) que o Hibernate utilizará para associar esta classe à tabela do banco de dados. Acredito que neste ponto alguns desenvolvedores já podem imaginar a econômia de código que isso pode trazer. Explicarei abaixo cada uma desta anotações, porém entendam que existem mais anotações, o que torna o Hibernate flexível para trabalhar com a maioria dos modelos de dados relacionais existentes.</p>
<ul>
<li><strong>@Entity:</strong> Especifica que a classe será uma entidade mapeada;</li>
<li><strong>@Table:</strong> Especifica que a classe representa uma tabela no banco;</li>
<ul>
<li><strong>name: </strong>Opcionalmente podemos informar o nome da tabela na anotação, caso ela não for informada o Hibernate vai assumir que o nome da tabela é o mesmo nome da classe.</li>
</ul>
<li><strong>@Id:</strong> Indica que o atributo anotado é a chave primária da tabela;</li>
<li><strong>@GenericGenerator:</strong> Define um gerador customizado de IDs. No nosso caso o auto-numerador do MySQL;</li>
<ul>
<li><strong>name: </strong>Nome que identifica o gerador (para ser utilizado como referência em outras anotações);</li>
<li><strong>strategy:</strong> A estratégia que esse gerador vai utilizar para gerar os identificadores. No nosso exemplo colocamos increment que diz que o seu valor será o incremento a partir da última geração.</li>
</ul>
<li><strong>@GeneratedValue:</strong> Ao usar esta anotação, indicamos que o valor do atributo anotado será gerado por um gerador;</li>
<ul>
<li><strong>generator:</strong> Nome do gerador customizado (o mesmo nome que está no atributo <strong>name</strong> da anotação <strong>@GenericGenerator</strong>).</li>
</ul>
<li><strong>@Column: </strong>Indica que o atributo representa uma coluna da tabela.</li>
<ul>
<li><strong>name:</strong>  Tem o mesmo funcionamento do atributo <strong>name</strong> da anotação <strong>@Table</strong>, ou seja, define o nome da coluna da tabela que o atributo está mapeando. Caso não for informado o Hibernate assume que o nome da coluna é igual o nome do atributo.</li>
</ul>
</ul>
<h2>Implementando a aplicação</h2>
<p>Vamos criar agora a classe que implementa os métodos CRUD do Livro. Na package <strong>spring_hibernateannotations.interfaces</strong> será criada a interface IBanco.java. Em nosso exemplo esta interface não parece muito útil, mas em um projeto maior podemos querer obrigar que toda classe que implementa a interface com banco de dados implemente as mesmas assinaturas de métodos.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> IBanco <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Livro InserirLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> AtualizarLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ApagarLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>Livro<span style="color: #339933;">&gt;</span> SelecionarLivrosPorTitulo<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> titulo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Livro SelecionarLivroPorCodigo<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> cod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<div>
<p>Vamos agora à implementação dessa interface. Na package <strong>spring_hibernateannotations</strong> será criada a classe <strong>BancoDados.java</strong>, que como mostrado na seção do arquivo de configuração, recebe a <em>SessionFactory</em> do Hibernate pela Injeção de Dependência do  Spring.</p>
<p>Colocarei nesta classe o controle de sessões (abrir e fechar <em>Sessions</em> do Hiberante) e transações, porém o mais viável é deixar Orientado a Aspecto, a partir de uma classe Transacao.java (<strong><em>Advice</em></strong>) e com os Pointcuts em <em>InserirLivro</em>, <em>AtualizarLivro</em> e <em>ApagarLivro</em>. Sempre executando um <em>beginTransaction </em>no @<em>Before</em>, um <em>commit</em> no @<em>AfterReturning</em> e um <em>rollback</em> no @<em>AfterThrowing. </em>Ou até mesmo aproveitando o controle automático de transações e sessões que o Spring proporciona, porém isso iria fugir do escopo deste post então fica para um próximo post ou para uma googleada da sua parte.. heheheh <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> BancoDados <span style="color: #000000; font-weight: bold;">implements</span> IBanco <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> SessionFactory sessionFactory<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Session sessao<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Transaction transacao<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setSessionFactory<span style="color: #009900;">&#40;</span>SessionFactory sessionFactory<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">sessionFactory</span> <span style="color: #339933;">=</span> sessionFactory<span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">sessao</span> <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Livro InserirLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				sessao <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
			transacao <span style="color: #339933;">=</span> sessao.<span style="color: #006633;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">int</span> cod <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Integer</span><span style="color: #009900;">&#41;</span> sessao.<span style="color: #006633;">save</span><span style="color: #009900;">&#40;</span>livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			livro.<span style="color: #006633;">setCod</span><span style="color: #009900;">&#40;</span>cod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>HibernateException e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">rollback</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
					sessao.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
			<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Throwable</span> e<span style="color: #009900;">&#41;</span>
			<span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao finalizar inserção: &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> livro<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> AtualizarLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				sessao <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
			transacao <span style="color: #339933;">=</span> sessao.<span style="color: #006633;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			sessao.<span style="color: #006633;">update</span><span style="color: #009900;">&#40;</span>livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>HibernateException e<span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">rollback</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
					sessao.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
			<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Throwable</span> e<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao finalizar atualização: &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ApagarLivro<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				sessao <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
			transacao <span style="color: #339933;">=</span> sessao.<span style="color: #006633;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			sessao.<span style="color: #006633;">delete</span><span style="color: #009900;">&#40;</span>livro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>HibernateException e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			transacao.<span style="color: #006633;">rollback</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
					sessao.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
			<span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Throwable</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao finalizar : &quot;</span> <span style="color: #339933;">+</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>Livro<span style="color: #339933;">&gt;</span> SelecionarLivrosPorTitulo<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> titulo<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			sessao <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		Criteria criteria <span style="color: #339933;">=</span> sessao.<span style="color: #006633;">createCriteria</span><span style="color: #009900;">&#40;</span>Livro.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		criteria.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>Restrictions.<span style="color: #006633;">like</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;titulo&quot;</span>, titulo<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> criteria.<span style="color: #006633;">list</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Livro SelecionarLivroPorCodigo<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> cod<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>sessao.<span style="color: #006633;">isOpen</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			sessao <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">openSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		Criteria criteria <span style="color: #339933;">=</span> sessao.<span style="color: #006633;">createCriteria</span><span style="color: #009900;">&#40;</span>Livro.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		criteria.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>Restrictions.<span style="color: #006633;">eq</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;cod&quot;</span>, cod<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Livro livro <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Livro<span style="color: #009900;">&#41;</span> criteria.<span style="color: #006633;">uniqueResult</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> livro<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>No post anterior era utilizado o<em> HibernateTemplate</em>, um facilitador do Spring para utilizar o Hibernate, porém desde a versão 3.x do Hibernate é aconselhável utilizar diretamente a<em> SessionFactory</em> ao invés do<em> HibernateTemplate</em> para deixar o Hibernate com mais controle das ações realizadas através das suas <em>Sessions</em>.</p>
<p>Bom, feitos todos os acessos, vamos criar a classe principal da aplicação. Ela é exatamente igual a do post anterior.</p>
<p>Vamos criar então a classe Main.java na package <strong>spring_hibernateannotations</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		ApplicationContext ctx <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassPathXmlApplicationContext<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;conf/conf.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Spring inicializado&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		BancoDados banco <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>BancoDados<span style="color: #009900;">&#41;</span> ctx.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;banco_dados&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		Livro livro1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Livro<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro1.<span style="color: #006633;">setTitulo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Spring + Hibernate&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Livro livro2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Livro<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro2.<span style="color: #006633;">setTitulo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Hibernate Avançado&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Objetos Livro inicializados&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		livro1 <span style="color: #339933;">=</span> banco.<span style="color: #006633;">InserirLivro</span><span style="color: #009900;">&#40;</span>livro1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro2 <span style="color: #339933;">=</span> banco.<span style="color: #006633;">InserirLivro</span><span style="color: #009900;">&#40;</span>livro2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Livros gravados no banco&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//zerando os objetos Livro</span>
		livro1 <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		livro2 <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Selecionando livros por código&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro1 <span style="color: #339933;">=</span> banco.<span style="color: #006633;">SelecionarLivroPorCodigo</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exibe<span style="color: #009900;">&#40;</span>livro1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro2 <span style="color: #339933;">=</span> banco.<span style="color: #006633;">SelecionarLivroPorCodigo</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exibe<span style="color: #009900;">&#40;</span>livro2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Selecionando livros que contenham 'Hibernate' no título&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		List<span style="color: #339933;">&lt;</span>Livro<span style="color: #339933;">&gt;</span> lista <span style="color: #339933;">=</span> banco.<span style="color: #006633;">SelecionarLivrosPorTitulo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Hibernate&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Livro l <span style="color: #339933;">:</span> lista<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			exibe<span style="color: #009900;">&#40;</span>l<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Atualizando livro&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		livro1.<span style="color: #006633;">setTitulo</span><span style="color: #009900;">&#40;</span>livro1.<span style="color: #006633;">getTitulo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot; Segunda Edição&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		banco.<span style="color: #006633;">AtualizarLivro</span><span style="color: #009900;">&#40;</span>livro1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Apagando livro&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		banco.<span style="color: #006633;">ApagarLivro</span><span style="color: #009900;">&#40;</span>livro2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> exibe<span style="color: #009900;">&#40;</span>Livro livro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>livro <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Livro não encontrado&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">else</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Livro -&gt; cod: &quot;</span> <span style="color: #339933;">+</span> livro.<span style="color: #006633;">getCod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; | Título: &quot;</span> <span style="color: #339933;">+</span> livro.<span style="color: #006633;">getTitulo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<div>
<p>O projeto está pronto para rodar:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/img6.png" target="_blank"><img class=" wp-image-551 aligncenter" src="http://www.javasimples.com.br/wp-content/uploads/img6.png" alt="Projeto Exemplo Spring + Hibernate + Annotations rodando" width="571" height="407" /></a></p>
<p>É isso aí pessoal, para projetos que são grandes ou que tem tendência de crescer é e essencial o uso de frameworks que tornam a codificação produtiva, a modificação nas camadas transparente, e que permitem ajustes a diferentes ambientes.</p>
<p>O Hibernate é muito mais do que foi explicado aqui, implementando o <em>C3PO</em> (connection pool framework) podemos deixa-lo preparado para quantidades grandes de acessos simultâneos, controle de cache para manter a performance de grandes massas de dados. Das annotations podemos fazer configurações de relacionamentos 1:1, 1:N, N:1, N:N, mapear chaves estrangeiras.</p>
<p>Espero que esta publicação ajude os leitores encontrarem o que procuram, seja maior conhecimento ou ajuda para fazer um trabalho para a empresa.</p>
<p>Agradeço ao Felipe Saab por sugerir esta publicação e ceder o espaço aqui para a mesma.</p>
<p>Até a próxima!!<br />
Abraço a todos!<br />
João Corrêa da Costa Junior.</p>
</div>
</div>
</div>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/hibernate-2/spring-3-1-hibernate-4-0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Framework Parte 6 -&gt; Injeção de Dependência via Anotações</title>
		<link>http://www.javasimples.com.br/spring-2/spring-framework-parte-6-injecao-de-dependencia-via-anotacoes</link>
		<comments>http://www.javasimples.com.br/spring-2/spring-framework-parte-6-injecao-de-dependencia-via-anotacoes#comments</comments>
		<pubDate>Tue, 14 Feb 2012 21:37:59 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation-config]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[anotação]]></category>
		<category><![CDATA[autowired]]></category>
		<category><![CDATA[component-scan]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[qualifier]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=540</guid>
		<description><![CDATA[Em todos os posts da série até agora nós utilizamos a injeção de dependência declarativamente, ou seja, definimos em um arquivo de configuração do Spring (um arquivo XML) qual bean ia ser injetado em qual e ai então o container fica responsável por fazer isso em tempo de execução. Bem legal, já vimos que funciona [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.javasimples.com.br/wp-content/uploads/Logo_Spring_252x150.png" target="_blank"><img class="size-full wp-image-559 alignleft" title="Logo_Spring_252x150" src="http://www.javasimples.com.br/wp-content/uploads/Logo_Spring_252x150.png" alt="" width="352" height="156" /></a>Em todos os posts da série até agora nós utilizamos a injeção de dependência declarativamente, ou seja, definimos em um arquivo de configuração do Spring (um arquivo XML) qual bean ia ser injetado em qual e ai então o container fica responsável por fazer isso em tempo de execução.</p>
<p>Bem legal, já vimos que funciona e funciona muito bem desse jeito.</p>
<p>Porém, &#8211; sempre tem um porém hehe &#8211;  conforme o sistema vai começando a crescer os arquivos de configuração começam a se tornar verdadeiras teias de aranha. Crescem muito!</p>
<p>E como a ideia do Spring é simplificar ao invés de complicar existe um jeito alternativo aos arquivos XML para configurar a injeção de dependência nos nossos beans: anotações.</p>
<p>Utilizando simples anotações nós conseguimos deixar o(s) arquivo(s) de configuração do Spring o mais simples possível e ainda assim deixar o container cuidar da injeção de dependência.</p>
<p><span id="more-540"></span></p>
<h1><strong>NOSSA APLICAÇÃO</strong></h1>
<p>Vamos desenvolver um pequeno programa para simular o funcionamento de um computador então.</p>
<p>O projeto vai ter a seguinte estrutura:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/estrutura_projeto1.png" target="_blank"><img class="aligncenter size-full wp-image-566" title="estrutura_projeto" src="http://www.javasimples.com.br/wp-content/uploads/estrutura_projeto1.png" alt="" width="330" height="325" /></a></p>
<p>OBS: a pasta <em>lib</em> contém todas as bibliotecas necessárias para rodar o projeto.</p>
<p>Vamos começar dando uma olhada no pacote <em>br.blog.javasimples.spring.pecas</em> para vermos as interfaces que definem as pecas do computador:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos necessários para uma peça do computador.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Peca <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos necessários para um Monitor.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Monitor <span style="color: #000000; font-weight: bold;">extends</span> Peca <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Escreve uma mensagem na tela.
	 */</span>
	<span style="color: #000066; font-weight: bold;">void</span> escreverNaTela<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> mensagem<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos necessários para um Processador.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Processador <span style="color: #000000; font-weight: bold;">extends</span> Peca <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Soma dois inteiros.
	 */</span>
	<span style="color: #000066; font-weight: bold;">int</span> soma<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> x, <span style="color: #000066; font-weight: bold;">int</span> y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos dar uma olhada em como as implementações dessas interfaces funcionam (pacote <em>br.blog.javasimples.spring.pecas.impl</em>):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um monitor CRT de 17 polegadas.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Monitor17 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> FREQUENCIA <span style="color: #339933;">=</span> <span style="color: #cc66cc;">60</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Iniciando o monitor [&quot;</span> <span style="color: #339933;">+</span> FREQUENCIA <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Hz];&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> escreverNaTela<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> mensagem<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[&quot;</span> <span style="color: #339933;">+</span> mensagem <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um processador DualCore.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> DualCore <span style="color: #000000; font-weight: bold;">implements</span> Processador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">double</span> FRQUENCIA <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2.6</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> NUCLEOS <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Iniciando o processador [&quot;</span> <span style="color: #339933;">+</span> FRQUENCIA <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;GHz, &quot;</span> <span style="color: #339933;">+</span> NUCLEOS <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; núcleos];&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> soma<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> x, <span style="color: #000066; font-weight: bold;">int</span> y<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> x <span style="color: #339933;">+</span> y<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Cada implementação é específica de um produto, ou seja, temos um monitor CRT de 17&#8221; que só suporta 60Hz e um processador DualCore (Intel) cuja frequência é 2.6GHz.</p>
<p>E o computador? Como fica?</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa o computador.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Computador<span style="color: #009900;">&#40;</span>Processador processador, Monitor monitor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">processador</span> <span style="color: #339933;">=</span> processador<span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">monitor</span> <span style="color: #339933;">=</span> monitor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Ligando computador...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		processador.<span style="color: #006633;">ligar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		monitor.<span style="color: #006633;">ligar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Computador ligado.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> somar<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> x, <span style="color: #000066; font-weight: bold;">int</span> y<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		monitor.<span style="color: #006633;">escreverNaTela</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;%d + %d = %d&quot;</span>, x, y, processador.<span style="color: #006633;">soma</span><span style="color: #009900;">&#40;</span>x, y<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O computador foi escrito seguindo as melhores práticas de desenvolvimento conforme já conversamos na  <a title="Spring Framework Parte 1 -&gt; Dependency Injection" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-1-dependency-injection" target="_blank">Parte 1</a> da série né:</p>
<ul>
<li>Programação orientada a interfaces e não a implementações: perceba que o computador não sabe se na sua placa mãe tem um processador Intel ou AMD, ele só sabe que tem um processador que sabe como ligar e somar;</li>
<li>Injeção de dependência: perceba que todas as dependências do computador são injetadas nele através do seu construtor, com isso ganhamos muita flexibilidade para futuras mudanças em relação a quais componentes devemos injetar no computador.</li>
</ul>
<p>E o arquivo de configuração ficou da seguinte maneira:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;computador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.Computador&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.DualCore&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.Monitor17&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<div>Para executar a nossa pequena aplicação temos a classe Main.java:</div>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		ApplicationContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassPathXmlApplicationContext<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;br/blog/javasimples/spring/config/applicationContext.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Computador pc <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Computador<span style="color: #009900;">&#41;</span> context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;computador&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		pc.<span style="color: #006633;">ligar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		pc.<span style="color: #006633;">somar</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O que acontece nela é que criamos o container do Spring a partir do arquivo de configuração, ligamos o computador e realizamos uma simples operação nele. Ao executar essa classe nós recebemos a seguinte saída:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">Ligando computador...
Iniciando o processador [2.6GHz, 2 núcleos];
Iniciando o monitor [60Hz];
Computador ligado.
[2 + 2 = 4]</pre></div></div>

<p>Legal, tudo funciona como nós já estávamos acostumados. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h1>Preparando o container</h1>
<p>Por padrão o container do Spring não vem com o suporte para injeção de dependência via anotações habilitado. Para fazer isso nós precisamos fazer uma pequena alteração no arquivo de configuração:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;computador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.Computador&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.DualCore&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.Monitor17&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>E como vamos utilizar a injeção de dependência via anotações nós já podemos remover as injeções declarativas do arquivo de configuração.</p>
<p>O Spring suporta algumas anotações para a injeção de dependência, são elas:</p>
<ul>
<li>A anotação do próprio Spring Framework<em> @Autowired;</em></li>
<li>A anotação <em>@Inject</em> da JSR-330 (Dependency Injection for Java);</li>
<li>A anotação <em>@Resource</em> da JSR-250 (Common Annotations for the Java Plataform).</li>
</ul>
<div>Hoje vamos ver somente a <em>@Autowired</em>. As outras são bem parecidas e ficam por sua conta o estudo ok? <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </div>
<h1>A anotação <em>@Autowired</em></h1>
<p>A anotação<em> @Autowired</em> pode ser utilizada em setters, construtores ou até mesmo em uma variável de classe &#8211; independe da sua visibilidade, ou seja, mesmo que private.</p>
<p>Na nossa aplicação podemos utilizá-la assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> Computador<span style="color: #009900;">&#40;</span>Processador processador, Monitor monitor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">processador</span> <span style="color: #339933;">=</span> processador<span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">monitor</span> <span style="color: #339933;">=</span> monitor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Eu, particularmente, estou mais acostumado a utilizar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Computador<span style="color: #009900;">&#40;</span>Processador processador, Monitor monitor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">processador</span> <span style="color: #339933;">=</span> processador<span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">monitor</span> <span style="color: #339933;">=</span> monitor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E a última maneira seria nos setters:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Processador getProcessador<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> processador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setProcessador<span style="color: #009900;">&#40;</span>Processador processador<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">processador</span> <span style="color: #339933;">=</span> processador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Monitor getMonitor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> monitor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setMonitor<span style="color: #009900;">&#40;</span>Monitor monitor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">monitor</span> <span style="color: #339933;">=</span> monitor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>OBS: os getters não são uma obrigatoriedade, coloquei apenas por convenção.</p>
<p>Simples assim, toda vez que precisarmos das dependências elas estarão lá! Para testar podemos rodar o projeto novamente e veremos que nada mudou na saída, ou seja, tudo ainda está funcionando! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>O Spring deve <strong>obrigatoriamente</strong> achar um bean para injetar no atributo anotado com <em>@Autowired</em>, caso contrário será lançada uma <em>NoSuchBeanDefinitionException</em>. Caso o atributo possa ter ou não valor, ou seja, se pode acontecer de o Spring não achar um bean para o atributo devemos setar a propriedade <em>required</em> da anotação para <em>false</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired<span style="color: #009900;">&#40;</span>required<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Porém quando fizer isso tome o cuidado de sempre verificar se o atributo está nulo ou não antes de utilizá-lo para evitar os famosos <em>NullPointerException</em>.</p>
<p>Outra coisa que devemos saber é que o Spring realiza uma busca por tipo (<em>byType</em>) para encontrar as dependências para atributos anotados com <em>@Autowired</em>, ou seja, como anotamos um atributo do tipo <em>br.blog.javasimples.spring.pecas.Monitor</em> o Spring vai procurar por algum bean que implemente essa interface para poder injetar no nosso computador.</p>
<p>Como disse anteriormente, caso ele não encontre nenhum bean será lançada uma <em>NoSuchBeanDefinitionException</em>.</p>
<p>Mas&#8230; &#8211; aqueles momentos em que você tem uma ideia que você acha que ninguém teve antes &#8211; e se ele encontrar mais de um bean que implemente essa interface?</p>
<p>Esse será o assunto do nosso próximo tópico, e só a nível de curiosidade, caso isso aconteça e não seja tratado o Spring também irá lançar uma <em>NoSuchBeanDefinitionException.</em></p>
<h1>Tratando dependências ambíguas com <em>@Qualifier</em></h1>
<p>E agora entra mais uma anotação para o nosso arsenal! hehehe</p>
<p>Para tratar dependências ambíguas o Spring nos oferece a anotação @<em>Qualifier</em> e algumas maneiras de utilizá-la. Antes de vermos todas essas maneiras vamos nos armar uma própria emboscada: criar mais um monitor para podermos simular tal erro.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um monitor LED de 22 polegadas.
 * 
 * @author Felipe
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED22 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> FREQUENCIA <span style="color: #339933;">=</span> <span style="color: #cc66cc;">75</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Iniciando o monitor [&quot;</span> <span style="color: #339933;">+</span> FREQUENCIA <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Hz];&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> escreverNaTela<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> mensagem<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[[[&quot;</span> <span style="color: #339933;">+</span> mensagem <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;]]]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Nosso novo monitor é LED, muito melhor do que o antigo CRT, e tem 22&#8221;, um tamanho bem agradável. Ele é tão melhor que até o seu método de escrever coloca umas frescurinhas a mais para tentar agradar o usuário (heheheh). Vamos adicioná-lo ao arquivo de configuração:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;computador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.Computador&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.DualCore&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.Monitor17&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitorLED22&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.MonitorLED22&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Se tentarmos rodar agora iremos ver a nossa tão comentada <em>NoSuchBeanDefinitionException.</em></p>
<p>Vamos ver então como podemos resolver isso de algumas maneiras diferentes.</p>
<h2>Selecionando de acordo com o ID</h2>
<p>Podemos especificar na anotação <em>@Qualifier</em> qual o ID do bean que queremos injetar:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;monitorLED22&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ao executar nossa aplicação assim será exibida a seguinte saída indicando que nosso computador está utilizando o monitor de 22&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">Ligando computador...
Iniciando o processador [2.6GHz, 2 núcleos];
Iniciando o monitor [75Hz];
Computador ligado.
[[[2 + 2 = 4]]]</pre></div></div>

<h2>Selecionando de acordo com um qualificador</h2>
<p>No exemplo anterior nós utilizamos o monitor novo, mas e se quiséssemos utilizar o antigo?</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;monitor&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Assim funciona porém não está muito intuitivo né&#8230; Um <em>Monitor</em> anotado com<em> @Qualifier(&#8220;monitor&#8221;)</em> não é muito fácil de entender né, em uma futura manutenção o pobre coitado vai ter que caçar no XML qual o bean que tem <em>id=&#8221;monitor&#8221;</em> para poder chegar na respectiva classe. Seria muito mais fácil se a anotação fosse<em> @Qualifier(&#8220;monitorCRT17&#8243;)</em> não seria?</p>
<p>A primeira ideia que vem na cabeça é: &#8220;beleza, vou mudar de id=&#8221;monitor&#8221; para id=&#8221;monitorCRT17&#8243;! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> &#8221;.</p>
<p>Como nossa aplicação é apenas um exemplo bem pequeno não teria problema nenhum. Mas imagine em uma aplicação grande que já está em produção.. O risco de gerar algum erro mudando o id do bean é um pouco maior.</p>
<p>Para evitar isso o Spring permite que informemos um qualificador para o bean. Podemos fazer isso de duas maneiras diferentes:</p>
<p>No XML de configuração:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;computador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.Computador&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.DualCore&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.Monitor17&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;qualifier</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;monitorCRT17&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitorLED22&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.MonitorLED22&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Ou então na própria classe:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;monitorCRT17&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Monitor17 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Criando qualificadores customizados</h2>
<p>Se você, assim como eu, acha que ficar se referindo diretamente aos IDs (ou até mesmo qualificadores) não é uma solução muito elegante o Spring permite que criemos nossos próprios qualificadores criando anotações que sejam anotadas com @<em>Qualifier</em>.</p>
<p>Vamos criar um qualificador que vai qualificar as tecnologias dos monitores, ou seja, @<em>MonitorLED</em> e @<em>MonitorCRT</em> (vou criar as anotações em um novo pacote <em>br.blog.javasimples.spring.pecas.anotacoes</em>):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Target<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>ElementType.<span style="color: #006633;">FIELD</span>, ElementType.<span style="color: #006633;">PARAMETER</span>, ElementType.<span style="color: #006633;">TYPE</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
@Qualifier
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> MonitorCRT <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Target<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>ElementType.<span style="color: #006633;">FIELD</span>, ElementType.<span style="color: #006633;">PARAMETER</span>, ElementType.<span style="color: #006633;">TYPE</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
@Qualifier
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> MonitorLED <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E vamos também anotar cada monitor com seu respectivo tipo:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@MonitorCRT
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Monitor17 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@MonitorLED
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED22 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Com isso podemos facilmente anotar a dependência do computador com a nossa nova anotação:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	@MonitorLED
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Nesse momento há aquele flash na sua cabeça (de novo) e você pergunta: &#8220;e se eu tiver 2 monitores de LED porém com tamanhos diferentes?&#8221;.</p>
<p>Vamos adicionar um novo monitor de LED ao nosso projeto então:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um monitor LED de 19 polegadas.
 * 
 * @author Felipe
 */</span>
@MonitorLED
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED19 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> FREQUENCIA <span style="color: #339933;">=</span> <span style="color: #cc66cc;">75</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> ligar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Iniciando o monitor [&quot;</span> <span style="color: #339933;">+</span> FREQUENCIA <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Hz];&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> escreverNaTela<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> mensagem<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[[&quot;</span> <span style="color: #339933;">+</span> mensagem <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;]]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;computador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.Computador&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;processador&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.DualCore&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.Monitor17&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitorLED19&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.MonitorLED19&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;monitorLED22&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring.pecas.impl.MonitorLED22&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Ao executar esse código caímos novamente na nossa adorável <em>NoSuchBeanDefinitionException.</em></p>
<p>Para resolver isso podemos utilizar combinações de qualificadores, ou seja, vamos criar mais alguns qualificadores para as polegadas:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Target<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>ElementType.<span style="color: #006633;">FIELD</span>, ElementType.<span style="color: #006633;">PARAMETER</span>, ElementType.<span style="color: #006633;">TYPE</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
@Qualifier
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> Monitor19 <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Target<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>ElementType.<span style="color: #006633;">FIELD</span>, ElementType.<span style="color: #006633;">PARAMETER</span>, ElementType.<span style="color: #006633;">TYPE</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
@Qualifier
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> Monitor22 <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos qualificar os monitores:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@MonitorLED
@Monitor19
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED19 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@MonitorLED
@Monitor22
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED22 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E por fim identificar corretamente qual monitor nosso computador irá possuir:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> Processador processador<span style="color: #339933;">;</span>
&nbsp;
	@Autowired
	@MonitorLED
	@Monitor19
	<span style="color: #000000; font-weight: bold;">private</span> Monitor monitor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ao executar esse código recebemos a seguinte saída indicando que nosso monitor de 19 entrou em ação:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">Ligando computador...
Iniciando o processador [2.6GHz, 2 núcleos];
Iniciando o monitor [75Hz];
Computador ligado.
[[2 + 2 = 4]]</pre></div></div>

<p>Na minha humilde opinião essa é a melhor e mais elegante solução para resolver o problema. Podemos fazer qualquer combinação com os qualificadores desde que ela identifique somente um bean.</p>
<h1>Descoberta automática de beans</h1>
<p>A utilização da tag <em>&lt;context:annotation-config /&gt;</em> no arquivo de configuração do Spring possibilita a utilização de várias anotações para a injeção de dependência porém não elimina a necessidade de declarar todos os seus beans no arquivo de configuração.</p>
<p>Em um sistema grande ainda teremos que declarar muitos beans no XML, o que acaba sendo um pouco chato&#8230;</p>
<p>Para evitar isso o Spring tem uma facilidade que possibilita que ele mesmo procure pelos beans em tempo de execução, ou seja, não precisamos declará-los via XML.</p>
<p>Para isso precisaremos fazer uma mudança no arquivo de configuração:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span>
<span style="color: #009900;">		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.spring&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Agora sim temos um belo arquivo de configuração em! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>A tag <em>&lt;context:component-scan base-package=&#8221;br.blog.javasimples.spring&#8221; /&gt;</em> possibilita o uso das anotações que anteriormente a tag <em>&lt;context:annotation-config /&gt;</em> possibilitava e ainda permite que o Spring procure sozinho por beans a partir do pacote <em>br.blog.javasimples.spring</em> (incluindo todos os subpacotes).</p>
<p>Porém o Spring só vai saber quais são os beans se eles estiverem identificados. Para fazer isso basta anotarmos os beans com uma das seguintes anotações:</p>
<ul>
<li>@<em>Component</em> &#8211; Uma anotação de propósitos gerais para identificar um bean;</li>
<li>@<em>Controller</em> &#8211; Indica que o bean é um controlador do Spring Web MVC;</li>
<li>@<em>Repository</em> &#8211; Indica que a classe é um repositório de dados;</li>
<li>@<em>Service</em> &#8211; Indica que a classe é um serviço.</li>
</ul>
<p>OBS: Para @<em>Controller</em>, @<em>Repository</em> e @<em>Service</em> existem situações em que essas anotações possuem um tratamento especial. Bateu a curiosidade? Go go Google! hehehe <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Como em nossa pequena aplicação nós não precisaremos de nenhum comportamento especial podemos simplesmente anotar as nossas classes que representam beans para o container com @<em>Component</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> DualCore <span style="color: #000000; font-weight: bold;">implements</span> Processador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span>
@MonitorCRT
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Monitor17 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span>
@Monitor19
@MonitorLED
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED19 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span>
@Monitor22
@MonitorLED
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MonitorLED22 <span style="color: #000000; font-weight: bold;">implements</span> Monitor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ao executarmos nossa aplicação agora tudo irá funcionar perfeitamente bem (ou pelo menos deveria hehehe).</p>
<p>É nesse momento que você tem sua última epifania do post e pergunta: &#8220;ué, lá na classe Main.java nós buscamos o computador pelo ID dele, como o Spring pegou a classe certa?&#8221;.</p>
<p>Muito bem observado! hehehe</p>
<p>Quando o Spring busca e cria automaticamente os beans ele seta o ID de cada bean com o nome da classe no padrão CamelCase para identificadores. Com isso <em>Computador</em> fica <em>computador.</em></p>
<p>Mas caso haja a necessidade de especificar qual será o ID do bean basta informar na própria anotação @<em>Component</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Component</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;pc&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Computador <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E na hora de recuperar ele basta utilizar o novo ID:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		ApplicationContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassPathXmlApplicationContext<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;br/blog/javasimples/spring/config/applicationContext.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Computador pc <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Computador<span style="color: #009900;">&#41;</span> context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;pc&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		pc.<span style="color: #006633;">ligar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		pc.<span style="color: #006633;">somar</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<h1>Conclusão</h1>
<p>E no fim do post temos um XML de configuração do Spring com apenas 1 linha! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Não sei quanto a vocês mas eu acho isso fantástico, onde for possível minimizar as configurações em XML é melhor pois torna o código bem mais legível e fácil de entender.</p>
<p>O download o projeto está <a title="Download do projeto" href="http://dl.dropbox.com/u/4918828/JavaSimples/Spring_Parte6.rar" target="_blank">disponível aqui</a>.</p>
<p>Todo e qualquer feedback é muito apreciado, não custa nada escrever o que achou, é rapidinho&#8230; hehehe</p>
<p>[]s e até a próxima,</p>
<p>Saab.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/spring-2/spring-framework-parte-6-injecao-de-dependencia-via-anotacoes/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Java + FLEX Parte 3 -&gt; Spring BlazeDS Integration + dpHibernate</title>
		<link>http://www.javasimples.com.br/flex/java-flex-parte-3-spring-blazeds-integration-dphibernate</link>
		<comments>http://www.javasimples.com.br/flex/java-flex-parte-3-spring-blazeds-integration-dphibernate#comments</comments>
		<pubDate>Sat, 06 Aug 2011 18:21:04 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[FLEX]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[adapter]]></category>
		<category><![CDATA[blazeds]]></category>
		<category><![CDATA[dphibernate]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=526</guid>
		<description><![CDATA[Neste post iremos ver como obter ainda mais produtividade no desenvolvimento de aplicações Java + FLEX adicionando o framework dpHibernate ao nosso projeto da Agenda, que foi criado na Parte 1 e melhorado na Parte 2 dessa série. Para utilizarmos o dpHibernate com todo o seu potencial precisaremos melhorar um pouco mais a nossa agenda [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/dpHibernate.png" target="_blank"><img class="aligncenter size-full wp-image-540" title="dpHibernate" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/dpHibernate.png" alt="" width="440" height="74" /></a></p>
<p><strong> </strong>Neste post iremos ver como obter ainda mais produtividade no desenvolvimento de aplicações Java + FLEX adicionando o framework <a title="dpHibernate" href="http://code.google.com/p/dphibernate/" target="_blank">dpHibernate</a> ao nosso projeto da Agenda, que foi criado na <a title="Java + FLEX Parte 1" href="http://www.javasimples.com.br/spring-2/java-spring-hibernate-flex-flash-builder-4-parte-1/" target="_blank">Parte 1</a> e melhorado na <a title="Java + FLEX Parte 2" href="http://www.javasimples.com.br/spring-2/java-spring-hibernate-flex-flash-builder-4-%E2%80%93-parte-2/" target="_blank">Parte 2</a> dessa série.</p>
<p>Para utilizarmos o dpHibernate com todo o seu potencial precisaremos melhorar um pouco mais a nossa agenda pois até agora temos apenas uma entidade no projeto: o Contato. Iremos adicionar a entidade Pessoa, sendo assim, Contato passará a ser uma entidade filha de Pessoa. Em outras palavras: uma Pessoa poderá ter nenhum ou muitos Contatos.</p>
<p>Mas vamos a um pouco de teoria antes (caso você já conheça o dpHibernate pode pular para a parte onde a ação começa a acontecer hehehe):</p>
<p><strong>O QUE É dpHibernate?</strong></p>
<p>De acordo com o <a title="dpHibernate" href="http://code.google.com/p/dphibernate/" target="_blank">site</a> do projeto:</p>
<blockquote><p>dpHibernate is a custom Flex Library and a custom BlazeDS Hibernate adapter that work together to give you support for lazy loading of hibernate objects from inside your flex applications.</p>
<p>dpHibernate é uma biblioteca para projetos Flex e um adaptador customizado do BlazeDS com suporte para o Hibernate que trabalham juntos para proporcionar suporte a lazy loading de objetos hibernate a partir da sua aplicação flex.</p></blockquote>
<p>Quer dizer, o dpHibernate é composto por dois projetos: uma biblioteca que será referenciada no projeto FLEX (um arquivo .swc) e outra biblioteca que vai ser referenciada no projeto Java (arquivo .jar) que vão proporcionar o lazy loading de objetos do hibernate a partir da sua aplicação FLEX!!</p>
<p>Vamos facilitar ainda mais com um exemplo: <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Vamos pensar nas entidades que vamos utilizar daqui a pouco: <em>Pessoa</em> e <em>Contato.</em></p>
<p>Na classe Pessoa nós vamos ter uma lista de Contato:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pessoa <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Outros atributos</span>
&nbsp;
    @OneToMany<span style="color: #009900;">&#40;</span>fetch<span style="color: #339933;">=</span>FetchType.<span style="color: #006633;">LAZY</span>, ...<span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">List</span> contatos<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Getters e setters</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Se antes de enviarmos uma Pessoa do Java para o FLEX não executarmos o método <em>getContatos()</em> do objeto Pessoa a lista não será inicializada pois está marcada para ser carregada preguiçosamente (FetchType.LAZY), e consequentemente não será enviada para o FLEX.</p>
<p>OBS: isso acontece porque estamos utilizando o <strong>Spring BlazeDS Integration</strong> no nosso projeto, e ele possui essa funcionalidade, somente listas <strong>inicializadas</strong> são enviadas para o FLEX.</p>
<p>Mas o que acontece caso eu queira a lista de contatos no FLEX? Ou inicializamos a lista antes de enviar o objeto para o FLEX, ou seja, executar o getter da lista, ou então quando precisarmos da lista no FLEX nós fazemos mais uma chamada remota para carregar a lista.</p>
<p>Pensando em performance o correto é carregar a lista somente quando realmente precisarmos dela, quando abrir a tela dos contatos por exemplo.</p>
<p>E é exatamente esta a função do dpHibernate! A primeira vez que uma lista for acessada (na aplicação FLEX) o dpHibernate vai verificar se essa lista já foi carregada ou não e caso ela não tenha sido ele irá se encarregar de fazer uma chamada remota para carregá-la. Tudo isso de uma maneira completamente transparente para o programador! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Agora que já sabemos como o dpHibernate funciona vamos preparar a nossa agenda adicionando a entidade Pessoa.</p>
<p><span id="more-526"></span></p>
<p><strong>ADICIONANDO A ENTIDADE PESSOA</strong></p>
<p>Na Parte 2 fizemos uma agenda que funcionava em torno de apenas uma entidade: Contato. Ou seja, tinhamos um DAO e um Service para o Contato. Tudo era relacionado com Contato.</p>
<p>Agora vamos adicionar um relacionamento ao contato, vamos seguir o seguinte diagrama de classes:</p>
<p style="text-align: center;"><strong> </strong><img class="aligncenter size-full wp-image-531" title="diagrama classe" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/diagrama-classe.png" alt="" width="439" height="157" /></p>
<p>Com isso a nossa aplicação não vai mais girar em torno de Contato, e sim em torno de Pessoa, ou seja, ao invés de um DAO e um Service para Contato, eles serão para Pessoa. Como Contato passou a ser uma entidade filha, ela vai ser gerenciada através do &#8220;seu pai&#8221;, a pessoa.</p>
<p>Como essa alteração vai ocupar um bom espaço aqui do post eu sugiro que baixe as <a title="Classes Base" href="http://dl.dropbox.com/u/4918828/JavaSimples/Spring_Flex_Parte_3_base.rar" target="_blank">classes (e o ddl para o banco) que utilizaremos como base</a>.</p>
<p>Aproveitei e dei uma arrumada no layout da nossa aplicação, agora ela está assim:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot1.png" target="_blank"><img class="aligncenter size-medium wp-image-549" title="screenshot1" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot1-300x141.png" alt="" width="300" height="141" /></a></p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot2.png" target="_blank"><img class="aligncenter size-medium wp-image-550" title="screenshot2" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot2-300x146.png" alt="" width="300" height="146" /></a></p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot3.png" target="_blank"><img class="aligncenter size-medium wp-image-551" title="screenshot3" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot3-300x222.png" alt="" width="300" height="222" /></a></p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot4.png" target="_blank"><img class="aligncenter size-medium wp-image-552" title="screenshot4" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/screenshot4-300x215.png" alt="" width="300" height="215" /></a></p>
<p>Muito bem, agora que a aplicação já está com um relacionamento podemos partir para a parte interessante do post, configurar o dpHibernate! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>CONFIGURANDO O dpHibernate</strong></p>
<p>A primeira coisa a se fazer é baixar as bibliotecas. Elas podem ser pegas através do <a title="Download dpHibernate" href="http://code.google.com/p/dphibernate/downloads/detail?name=2.0-RC6.zip" target="_blank">site do projeto</a> ou podem ser pegas <a title="dpHibernate do JavaSimples" href="http://dl.dropbox.com/u/4918828/JavaSimples/dpHibernateAdapter_java_simples.rar" target="_blank">aqui no Java Simples</a>.</p>
<p><strong>Por que pegar as bibliotecas aqui?</strong> Pois eu corrigi um pequeno probleminha no projeto (descrito nesse <a title="Problema com IDs do tipo Long" href="http://code.google.com/p/dphibernate/issues/detail?id=64" target="_blank">link</a>). O problema que acontece na última versão disponível do projeto é na deserialização de identificadores (o id da entidade) do tipo <em>java.lang.Long</em>, o deserializador do projeto se confunde e tenta converter o valor vindo do FLEX para o tipo <em>java.lang.Integer</em>. Apliquei um pequeno patch disponibilizado por um dos commiters do projeto e tudo passou a funcionar perfeitamente, portanto caso você &#8211; assim como eu &#8211; utilize o tipo <em>java.lang.Long</em> para os identificadores sinta-se a vontade para baixar as bibliotecas já corrigidas ou para aplicar o <a title="Patch para a correção de IDs java.lang.Long" href="http://code.google.com/p/dphibernate/issues/detail?id=64" target="_blank">patch</a> no projeto (os códigos fonte podem ser pegos através da <a title="dpHibernate" href="http://code.google.com/p/dphibernate" target="_blank">página do projeto</a>).</p>
<p>OBS: no pacote de bibliotecas disponíveis <a title="dpHibernate Java Simples" href="http://dl.dropbox.com/u/4918828/JavaSimples/dpHibernateAdapter_java_simples.rar" target="_blank">aqui no blog</a> também estão algumas bibliotecas adicionais necessárias para o correto funcionamento do projeto.</p>
<p>Com as bibliotecas baixadas basta adicionar os arquivos .jar no classpath do projeto Java e o arquivo .swc ao classpath do projeto FLEX.</p>
<p>Mãos à obra então! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Vamos começar alterando nossas entidades (classes do modelo). Para permitir que as classes sejam monitoradas pelo dpHibernate precisamos fazer apenas algumas alterações nelas: as classes Java devem estender <em>HibernateProxy</em> e sobrescrever o método <em>getProxyKey()</em> retornando um identificador único (o id funciona muito bem não? hehe) e as classes AS devem esternder <em>HibernateBean </em>e receber o metadado <em>[Managed]</em>.</p>
<p><strong>Pessoa.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Clase que representa uma pessoa na agenda.
 * Cada pessoa poderá ter vários {@link Contato contatos} (email, telefone,
 * site, ...).
 *
 * @author Felipe Saab
 */</span>
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;PESSOA&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pessoa <span style="color: #000000; font-weight: bold;">extends</span> HibernateProxy <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 3815773591498770002L<span style="color: #339933;">;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>strategy<span style="color: #339933;">=</span>GenerationType.<span style="color: #006633;">AUTO</span><span style="color: #009900;">&#41;</span>
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ID&quot;</span>, length<span style="color: #339933;">=</span><span style="color: #cc66cc;">11</span>, nullable<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Long</span> id<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;NOME&quot;</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span>, length <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
&nbsp;
	@OneToMany<span style="color: #009900;">&#40;</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>, mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;pessoa&quot;</span>, cascade <span style="color: #339933;">=</span> CascadeType.<span style="color: #006633;">ALL</span>, orphanRemoval <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">List</span> contatos<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getProxyKey<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        	<span style="color: #000000; font-weight: bold;">return</span> id<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Getters e Setters e outros métodos</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Contato.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um contato de uma {@link Pessoa pessoa} na agenda.
 *
 * @author Felipe Saab
 */</span>
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CONTATO&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato <span style="color: #000000; font-weight: bold;">extends</span> HibernateProxy <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>1549466344815889020L<span style="color: #339933;">;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>strategy <span style="color: #339933;">=</span> GenerationType.<span style="color: #006633;">AUTO</span><span style="color: #009900;">&#41;</span>
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ID&quot;</span>, length <span style="color: #339933;">=</span> <span style="color: #cc66cc;">11</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Long</span> id<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;TIPO&quot;</span>, length <span style="color: #339933;">=</span> <span style="color: #cc66cc;">50</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> tipo<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CONTATO&quot;</span>, length <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> contato<span style="color: #339933;">;</span>
&nbsp;
	@ManyToOne<span style="color: #009900;">&#40;</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span><span style="color: #009900;">&#41;</span>
	@JoinColumn<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ID_PESSOA&quot;</span>, referencedColumnName <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ID&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Pessoa pessoa<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getProxyKey<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> id<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Getters e Setters e outros métodos</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Pessoa.as</strong></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #66cc66;">&#91;</span>Managed<span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#91;</span>RemoteClass<span style="color: #66cc66;">&#40;</span>alias=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.model.Pessoa&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pessoa <span style="color: #0066CC;">extends</span> HibernateBean
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> id:<span style="color: #0066CC;">Number</span>;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> nome:<span style="color: #0066CC;">String</span>;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> contatos:ArrayCollection;
&nbsp;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> Pessoa<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> addContato<span style="color: #66cc66;">&#40;</span>contato:Contato<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">!</span>contatos<span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			contatos = <span style="color: #000000; font-weight: bold;">new</span> ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
		contatos.<span style="color: #006600;">addItem</span><span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;
		contato.<span style="color: #006600;">pessoa</span> = <span style="color: #0066CC;">this</span>;
		contatos.<span style="color: #006600;">refresh</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> removeContato<span style="color: #66cc66;">&#40;</span>contato:Contato<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">!</span>contatos<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">return</span>;
		<span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">index</span>:<span style="color: #0066CC;">int</span> = contatos.<span style="color: #006600;">getItemIndex</span><span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #0066CC;">index</span> == -<span style="color: #cc66cc;">1</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">return</span>;
		contatos.<span style="color: #006600;">removeItemAt</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">index</span><span style="color: #66cc66;">&#41;</span>;
		contatos.<span style="color: #006600;">refresh</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Contato.as</strong></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #66cc66;">&#91;</span>Managed<span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#91;</span>RemoteClass<span style="color: #66cc66;">&#40;</span>alias=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.model.Contato&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato <span style="color: #0066CC;">extends</span> HibernateBean
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> id:<span style="color: #0066CC;">Number</span>;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> tipo:<span style="color: #0066CC;">String</span>;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> contato:<span style="color: #0066CC;">String</span>;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> pessoa:Pessoa;
&nbsp;
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Modelo preparado, podemos partir então para a configuração da aplicação web e do Spring:</p>
<p>A estrutura de pastas e arquivos da aplicação web ficou assim:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/estrutura_pacotes1.png" target="_blank"><img class="aligncenter size-medium wp-image-569" title="estrutura_pacotes" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/estrutura_pacotes1-201x300.png" alt="" width="201" height="300" /></a></p>
<p>Passamos a ter 3 arquivos de configuração do Spring: <em>WEB-INF\spring\applicationContext.xml</em>, <em>WEB-INF\spring\persistence-config.xml</em> e <em>WEB-INF\spring\flex-config.xml</em>. Mas vamos entendê-los mais a fundo nas próximas linhas, vamos começar do começo: <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>web.xml</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;web-app</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span> </span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:web</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;WebApp_ID&quot;</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;2.4&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Listener responsável por iniciar o container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.context.ContextLoaderListener<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Localização do arquivo de configuração para o listener configurar o </span>
<span style="color: #808080; font-style: italic;">		container --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/WEB-INF/spring/applicationContext.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/context-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Filtro para manter sempre - e apenas! - uma sessão do Hibernate aberta --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>openSessionInViewFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- DispatcherServlet para o Spring BlazeDS Integration --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>springMessageBroker<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.servlet.DispatcherServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/WEB-INF/spring/flex-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Mappings --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>openSessionInViewFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>springMessageBroker<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/messagebroker/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/web-app<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>No deployment descriptor (vulgo <em>web.xml</em> hehehe) definimos que o Spring vai inicializar um container para a aplicação através do listener <em>ContextLoaderListener</em>, que o Hibernate vai ter somente uma sessão aberta durante toda a vida da nossa aplicação (isso é essencial para o lazy loading funcionar corretamente) através do filtro <em>OpenSessionInViewFilter</em>, e por fim definimos o <em>DispatcherServlet</em> do Spring MVC requerido pelo <strong>Spring BlazeDS Integration</strong> (como vimos na Parte 2).</p>
<p>Com isso já achamos onde são usados 2 arquivos de configuração do Spring: o <em>applicationContext.xml</em> vai conter os beans que poderão ser acessados de qualquer lugar da aplicação pois estarão no contexto da aplicação (<em>ApplicationContext</em>) e o <em>flex-config.xml</em> que é arquivo de configuração para o <em>DispatcherServlet</em> vai conter as configurações do <strong>Spring BlazeDS Integration</strong>.</p>
<p>OBS: caso não se lembre do servlet <em>DispatcherServlet </em>ou caso não conheça o <strong>Spring MVC </strong>eu sugiro que dê uma olhada no post: <strong><a title="Spring Framework Parte 5 -&gt; Spring Web MVC" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-5-spring-web-mvc/" target="_blank">Spring Framework Parte 5 -&gt; Spring Web MVC</a></strong>.</p>
<p>Vamos por partes então, primeiro o <strong>applicationContext.xml</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span> <span style="color: #000066;">xmlns:p</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/p&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context/spring-context.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Configurações de persistência --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;import</span> <span style="color: #000066;">resource</span>=<span style="color: #ff0000;">&quot;/spring/persistence-config.xml&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Habilita a injeção de dependência através de anotações --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Faz com que os Services sejam beans gerenciados pelo container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.service.impl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Faz com que os DAOs sejam beans gerenciados pelo container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.dao.impl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>E de cara já vimos onde é utilizado o último arquivo de configuração, essa foi rápida né! hehehe</p>
<p>Os maiores motivos para a separação dos arquivos de configuração foi para eles ficarem mais legíveis e coesos, sendo assim o arquivo <em>WEB-INF\spring\persistence-config.xml</em> vai conter somente os beans relacionados à persistência dos dados. Para carregar esses beans no contexto da aplicação utilizamos a tag <em>&lt;import&gt;</em>, com isso todos os beans que estiverem dentro do arquivo <em>persistence-config.xml</em> também serão carregados no contexto da aplicação.</p>
<p>Mas no <em>applicationContext.xml</em> além da inclusão dos beans relacionados à persistência foram definidas também as tags responsáveis por permitir a injeção de dependência e o gerenciamento dos Services e DAOs através de anotações.</p>
<p><strong>persistence-config.xml</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span> </span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:p</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/p&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:tx</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/tx&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</span>
<span style="color: #009900;">						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- DataSource --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;driverClassName&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.mysql.jdbc.Driver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://localhost:3306/javasimples_agenda<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;username&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>usuario<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>senha<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Hibernate SessionFactory --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ref</span> <span style="color: #000066;">local</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #808080; font-style: italic;">&lt;!-- Carrega todos os Beans --&gt;</span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;packagesToScan&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.blog.javasimples.agenda.model<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #808080; font-style: italic;">&lt;!-- Propriedades do Hibernate --&gt;</span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;hibernateProperties&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.dialect&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>org.hibernate.dialect.MySQL5InnoDBDialect<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.show_sql&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.format_sql&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Habilita as transações nas operações do banco --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;transactionManager&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.HibernateTransactionManager&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ref</span> <span style="color: #000066;">bean</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tx:annotation-driven</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Apesar do arquivo ser um pouco grande não há muita coisa a ser dita sobre esses beans, foram definidos um <em>DriverManagerDataSource</em> para conversar com o banco de dados, a <em>SessionFactory</em> responsável pelo mapeamento do Hibernate e o <em>HibernateTransactionManager</em> responsável pelas transações das operações do Hibernate.</p>
<p>Dando continuidade aos arquivos de configuração vamos ver os beans que serão definidos no escopo do <em>DispatcherServlet</em> do <strong>Spring BlazeDS Integration</strong>:</p>
<p><strong>flex-config.xml</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span> <span style="color: #000066;">xmlns:p</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/p&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:flex</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/flex&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex/spring-flex-1.0.xsd</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context </span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context/spring-context.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Injeção de dependência (e outras configurações) através de anotações --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- MessageBroker vai utilizar o adaptador do dpHibernate --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;flex:message-broker<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;flex:remoting-service</span> <span style="color: #000066;">default-adapter-id</span>=<span style="color: #ff0000;">&quot;dpHibernateRemotingAdapter&quot;</span> <span style="color: #000066;">default-channels</span>=<span style="color: #ff0000;">&quot;my-amf&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/flex:message-broker<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Adaptador remoto que vai interceptar as mensagens do FLEX e vai aplicar a lógica do dpHibernate --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dpHibernateRemotingAdapter&quot;</span></span>
<span style="color: #009900;">		<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.flex.core.ManageableComponentFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;org.dphibernate.adapters.SpringAwareRemotingAdapter&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;properties&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				{
				&quot;dpHibernate&quot; :
				{
				&quot;serializerFactory&quot; : &quot;org.dphibernate.serialization.SpringContextSerializerFactory&quot;
				}
				}
	        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Serviço que será utilizado para o lazy loading --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataAccessService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.services.SpringDataAccessService&quot;</span> <span style="color: #000066;">autowire</span>=<span style="color: #ff0000;">&quot;constructor&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;flex:remoting-destination</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Cache que evita que um mesmo objeto seja serializado mais de uma vez --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dpHibernateCache&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.serialization.DPHibernateCache&quot;</span> <span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Serializador e Deserializador que enviam (serializam) e recebem (deserializam) os objetos do FLEX --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dpHibernateSerializer&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.serialization.HibernateSerializer&quot;</span> <span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dpHibernateDeserializer&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.serialization.HibernateDeserializer&quot;</span> <span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Gerencia o CRUD das entidades. --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;objectChangeUpdater&quot;</span></span>
<span style="color: #009900;">		<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.persistence.state.BaseSpringWiredObjectChangeUpdater&quot;</span></span>
<span style="color: #009900;">		<span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Utilizado nas operações CRUD para converter os proxys novamente para as entidades --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;hibernateProxyResolver&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.persistence.state.DbProxyResolver&quot;</span> <span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Aqui é onde a mágica do dpHibernate acontece! hehehe</p>
<p>Começando de cima para baixo temos:</p>
<p>A injeção de dependência nesse contexto (<em>DispatcherServlet</em>) também poderá ser utilizada com anotações graças à tag <em>&lt;context:annotation-config /&gt;</em>, definimos o MessageBroker (não lembra dele? dê uma lidinha rápida na <a title="Java + FLEX Parte 1" href="http://www.javasimples.com.br/spring-2/java-spring-hibernate-flex-flash-builder-4-parte-1/" target="_blank">Parte 1</a> então) através da tag <em>&lt;flex:message-broker&gt;</em> e definimos que o adaptador utilizado para processar as requisições será o <em>dpHibernateRemotingAdapter</em> (definido imediatamente abaixo).</p>
<p>Após o adaptador é definido o <em>dataAccessService</em> que vamos utilizar para cuidar das operações CRUD e do lazy loading das nossas entidades, com isso os nossos services vão conter apenas as regras de negócio envolvidas nas entidades, nada mais de CRUD nos services! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>OBS: a tag <em>&lt;flex:remoting-destination /&gt;</em> é responsável por explicitamente definir o bean como um <em>destination</em> para o FLEX, ou seja, quando criarmos um <em>RemoteObject </em>podemos definir o <strong>destination = dataAccessService</strong> e essa classe (<em>org.dphibernate.services.SpringDataAccessService</em>) vai receber as requisições.</p>
<p>Logo em seguida é definida uma classe responsável por cachear os objetos serializados para evitar que eles sejam serializados mais de uma vez (assunto meio paralelo, então deixa pra outra hora.. heheh) e o serializador e o deserializador utilizados para converter os objetos Java para AMF e vice versa.</p>
<p>Depois temos o <em>objectChangeUpdater</em> que &#8211; de um jeito muito inteligente &#8211; cuida de todo o CRUD das entidades gerenciadas pelo dpHibernate. Aconselho fortemente a fazer checkout do código fonte e dar uma olhada. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>E por fim temos o <em>hiberanteProxyResolver</em>, classe responsável por manter a integridade dos objetos que ele vai proxiar entre as diversas operações que realizar. Toda classe gerenciada pelo dpHiberante possui uma <strong>proxyKey</strong>, tanto que sobrescrevemos o getter dessa chave nas entidades para garantir que seja retornado sempre um valor único. O dpHibernate utiliza essa chave para saber qual objeto foi enviado do FLEX para o Java e utilizar o objeto que já estava na sessão do hibernate, mantendo assim a integridade dos dados. Bem simples e bem legal não? <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Bom, é isso! Com isso terminamos de configurar o dpHibernate do lado servidor da nossa aplicação. Vamos passar então para o lado do cliente, a aplicação FLEX:</p>
<p><strong>AgendaF.mxml</strong></p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;">&lt;?xml version=<span style="color: #ff0000;">&quot;1.0&quot;</span> encoding=<span style="color: #ff0000;">&quot;utf-8&quot;</span>?<span style="color: #7400FF;">&gt;</span></span>
<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Application</span> xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span></span>
<span style="color: #000000;">			   xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span></span>
<span style="color: #000000;">			   xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span></span>
<span style="color: #000000;">			   xmlns:dphibernate=<span style="color: #ff0000;">&quot;http://www.dphibernate.org/2010/mxml&quot;</span></span>
<span style="color: #000000;">			   applicationComplete=<span style="color: #ff0000;">&quot;onApplicationComplete(event)&quot;</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;">&lt;!<span style="color: #66cc66;">&#91;</span>CDATA<span style="color: #66cc66;">&#91;</span></span>
&nbsp;
<span style="color: #000000;">			// Imports...</span>
&nbsp;
<span style="color: #000000;">			private var pessoaService:RemoteObject=new RemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;pessoaService&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">			<span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span></span>
<span style="color: #000000;">			private var agenda:ArrayCollection=new ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Carrega todas as pessoas já cadastradas.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function getAgenda<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				var token:AsyncToken=pessoaService.getAgenda<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				token.addResponder<span style="color: #66cc66;">&#40;</span>new mx.rpc.Responder<span style="color: #66cc66;">&#40;</span>getAgendaSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Agenda carregada com sucesso.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function getAgendaSucesso<span style="color: #66cc66;">&#40;</span>event:ResultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				this.agenda=event.result as ArrayCollection;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Quando ocorrer algum erro nas chamadas remotas.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function erro<span style="color: #66cc66;">&#40;</span>event:FaultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Ocorreu o seguinte erro: &quot;</span> + event.fault.faultString<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Inicializações gerais.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			protected function onApplicationComplete<span style="color: #66cc66;">&#40;</span>event:FlexEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				var remoteObject:HibernateRemoteObject=new HibernateRemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;dataAccessService&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				HibernateManaged.defaultHibernateService=remoteObject;</span>
<span style="color: #000000;">				this.getAgenda<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
<span style="color: #000000;">		<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Form</span> width=<span style="color: #ff0000;">&quot;500&quot;</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Nome&quot;</span></span>
<span style="color: #000000;">					 width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">					 direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> id=<span style="color: #ff0000;">&quot;txtNome&quot;</span></span>
<span style="color: #000000;">						 width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Button</span> label=<span style="color: #ff0000;">&quot;Salvar&quot;</span></span>
<span style="color: #000000;">					  click=<span style="color: #ff0000;">&quot;this.salvaPessoa()&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> id=<span style="color: #ff0000;">&quot;grdPessoa&quot;</span></span>
<span style="color: #000000;">						 width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">						 dataProvider=<span style="color: #ff0000;">&quot;{this.agenda}&quot;</span></span>
<span style="color: #000000;">						 doubleClickEnabled=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #000000;">						 doubleClick=<span style="color: #ff0000;">&quot;mostraContatos(agenda.getItemAt(grdPessoa.selectedIndex))&quot;</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Nome&quot;</span></span>
<span style="color: #000000;">									   dataField=<span style="color: #ff0000;">&quot;nome&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
&nbsp;
					<span style="color: #000000;"><span style="color: #808080; font-style: italic;">&lt;!-- Coluna que vai ter o botão dos contatos --&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Contatos&quot;</span></span>
<span style="color: #000000;">									   width=<span style="color: #ff0000;">&quot;60&quot;</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> horizontalAlign=<span style="color: #ff0000;">&quot;center&quot;</span><span style="color: #7400FF;">&gt;</span></span>
									<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Button</span> label=<span style="color: #ff0000;">&quot;Exibir&quot;</span></span>
<span style="color: #000000;">											   icon=<span style="color: #ff0000;">&quot;@Embed('br/blog/javasimples/agenda/imagens/contatos.png')&quot;</span></span>
<span style="color: #000000;">											   width=<span style="color: #ff0000;">&quot;25&quot;</span></span>
<span style="color: #000000;">											   click=<span style="color: #ff0000;">&quot;outerDocument.mostraContatos(data)&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGridColumn</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
					<span style="color: #000000;"><span style="color: #808080; font-style: italic;">&lt;!-- Coluna que vai ter o botão para a exclusão --&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Apagar&quot;</span></span>
<span style="color: #000000;">									   width=<span style="color: #ff0000;">&quot;50&quot;</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> horizontalAlign=<span style="color: #ff0000;">&quot;center&quot;</span><span style="color: #7400FF;">&gt;</span></span>
									<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Button</span> icon=<span style="color: #ff0000;">&quot;@Embed('br/blog/javasimples/agenda/imagens/apagar.png')&quot;</span></span>
<span style="color: #000000;">											   width=<span style="color: #ff0000;">&quot;25&quot;</span></span>
<span style="color: #000000;">											   click=<span style="color: #ff0000;">&quot;outerDocument.apagaPessoa(data)&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGridColumn</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/s:Application</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>Nossa aplicação sofreu uma pequena mudança apenas para ter a interface melhorada, foram adicionados dois ícones na grid: um para mostrar os contatos e outro para remover a pessoa. Ambas funcionalidades serão vistas no próximo tópico, vamos nos atentar primeiro à configuração do dpHibernate.</p>
<p>É na função <em>onApplicationComplete</em> que nós faremos a única configuração no projeto FLEX: vamos criar um Service padrão para o dpHibernate poder utilizar para as operações CRUD. Isso é feito criando um <em>HibernateRemoteObject </em>que vai enviar as requisições para o service que definimos no contexto do <em>DispatcherServlet</em>: o <em>dataAccessService</em>.</p>
<p>E pronto! Java e FLEX configurados!! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>SALVAR, ATUALIZAR E APAGAR REGISTROS<br />
</strong></p>
<p>Vamos então utilizar as vantagens desse mundo de configurações né&#8230; hehehehe</p>
<p>Repare no código do arquivo AgendaF.mxml (listagem anterior) que quando o usuário clicar no botão Salvar será chamada a função <em>salvaPessoa()</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Salva uma pessoa.
 */</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> salvaPessoa<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> pessoa:Pessoa=<span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	pessoa.<span style="color: #006600;">nome</span>=txtNome.<span style="color: #0066CC;">text</span>;
	pessoa.<span style="color: #006600;">contatos</span>=<span style="color: #000000; font-weight: bold;">new</span> ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">var</span> token:AsyncToken=pessoa.<span style="color: #006600;">save</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	token.<span style="color: #006600;">addResponder</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">Responder</span><span style="color: #66cc66;">&#40;</span>salvaPessoaSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Pessoa salva com sucesso.
 */</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> salvaPessoaSucesso<span style="color: #66cc66;">&#40;</span>event:ResultEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	Alert.<span style="color: #0066CC;">show</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Pessoa salva com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Recupera a agenda com todas as pessoas</span>
	<span style="color: #0066CC;">this</span>.<span style="color: #006600;">getAgenda</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Para salvar ou atualizar (save ou update) uma entidade gerenciada pelo dpHiberante devemos apenas chamar a sua função <em>save()</em>. Ela funciona do mesmo modo que uma chamada a um método remoto, ou seja, retorna um AsyncToken referente à chamada para podermos saber se houve sucesso ou erro durante sua execução.</p>
<p>Se repararmos no código do botão da grid referente a apagar a pessoa veremos que ele chama a função <em>apagaPessoa()</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Apaga a pessoa e seus contatos.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> apagaPessoa<span style="color: #66cc66;">&#40;</span>obj:<span style="color: #0066CC;">Object</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> pessoa:Pessoa=obj as Pessoa;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>pessoa<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">var</span> token:AsyncToken=pessoa.<span style="color: #006600;">deleteRecord</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		token.<span style="color: #006600;">addResponder</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">Responder</span><span style="color: #66cc66;">&#40;</span>apagaPessoaSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Pessoa apagada com sucesso.
 */</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> apagaPessoaSucesso<span style="color: #66cc66;">&#40;</span>event:ResultEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	Alert.<span style="color: #0066CC;">show</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Pessoa apagada com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Recupera a agenda com todas as pessoas</span>
	<span style="color: #0066CC;">this</span>.<span style="color: #006600;">getAgenda</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Do mesmo modo que a função <em>save()</em> as entidades gerenciadas pelo dpHibernate passam a ter também a função <em>deleteRecord()</em> que é um tanto quanto intuitiva certo? hehehe Apaga do banco a entidade que chamou a função.</p>
<p>E com isso terminamos o cadastro básico de Pessoa, vamos agora colocar os contatos na aplicação:</p>
<p><strong>Contatos.mxml</strong></p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;">&lt;?xml version=<span style="color: #ff0000;">&quot;1.0&quot;</span> encoding=<span style="color: #ff0000;">&quot;utf-8&quot;</span>?<span style="color: #7400FF;">&gt;</span></span>
<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TitleWindow</span> xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span></span>
<span style="color: #000000;">			   xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span></span>
<span style="color: #000000;">			   xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span></span>
<span style="color: #000000;">			   creationComplete=<span style="color: #ff0000;">&quot;init()&quot;</span></span>
<span style="color: #000000;">			   title=<span style="color: #ff0000;">&quot;Contatos&quot;</span></span>
<span style="color: #000000;">			   close=<span style="color: #ff0000;">&quot;fechaJanela()&quot;</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;">&lt;!<span style="color: #66cc66;">&#91;</span>CDATA<span style="color: #66cc66;">&#91;</span></span>
&nbsp;
<span style="color: #000000;">			// Imports...</span>
&nbsp;
<span style="color: #000000;">			<span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span></span>
<span style="color: #000000;">			private var tipos:ArrayCollection;</span>
&nbsp;
<span style="color: #000000;">			<span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span></span>
<span style="color: #000000;">			public var pessoa:Pessoa;</span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Inicializações.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function init<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				this.tipos=new ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				this.tipos.addItem<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Residencial&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				this.tipos.addItem<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Comercial&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				this.tipos.addItem<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Celular&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				this.tipos.addItem<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Email&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				this.tipos.addItem<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Website&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Fecha o formulário.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function fechaJanela<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				PopUpManager.removePopUp<span style="color: #66cc66;">&#40;</span>this<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Cria um novo contato e adiciona a lista de contatos da pessoa.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function criaContato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				var contato:Contato=new Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				contato.tipo=cbbTipo.selectedItem;</span>
<span style="color: #000000;">				contato.contato=txtContato.text;</span>
<span style="color: #000000;">				contato.pessoa=this.pessoa;</span>
&nbsp;
<span style="color: #000000;">				if <span style="color: #66cc66;">&#40;</span>pessoa.contatos == null<span style="color: #66cc66;">&#41;</span></span>
<span style="color: #000000;">					pessoa.contatos=new ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">				pessoa.addContato<span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				var token:AsyncToken=pessoa.save<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				token.addResponder<span style="color: #66cc66;">&#40;</span>new mx.rpc.Responder<span style="color: #66cc66;">&#40;</span>contatoSalvo, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Confirmação de que o contato foi inserido.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function contatoSalvo<span style="color: #66cc66;">&#40;</span>event:ResultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Contato salvo com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Quando ocorrer algum erro nas chamadas remotas.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			private function erro<span style="color: #66cc66;">&#40;</span>event:FaultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Ocorreu o seguinte erro: &quot;</span> + event.fault.faultString<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">			/**</span>
<span style="color: #000000;">			 * Remove o contato da lista de contatos da pessoa.</span>
<span style="color: #000000;">			 */</span>
<span style="color: #000000;">			public function apagaContato<span style="color: #66cc66;">&#40;</span>obj:Object<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">				var c:Contato = obj as Contato;</span>
<span style="color: #000000;">				pessoa.removeContato<span style="color: #66cc66;">&#40;</span>c<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">				c.deleteRecord<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">			<span style="color: #66cc66;">&#125;</span></span>
<span style="color: #000000;">		<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Tipo&quot;</span></span>
<span style="color: #000000;">					 width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">					 direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:ComboBox</span> id=<span style="color: #ff0000;">&quot;cbbTipo&quot;</span></span>
<span style="color: #000000;">						dataProvider=<span style="color: #ff0000;">&quot;{tipos}&quot;</span></span>
<span style="color: #000000;">						selectedIndex=<span style="color: #ff0000;">&quot;0&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">					   height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Button</span> label=<span style="color: #ff0000;">&quot;Adicionar&quot;</span></span>
<span style="color: #000000;">					  click=<span style="color: #ff0000;">&quot;criaContato()&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Contato&quot;</span></span>
<span style="color: #000000;">					 direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span></span>
<span style="color: #000000;">					 width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> id=<span style="color: #ff0000;">&quot;txtContato&quot;</span></span>
<span style="color: #000000;">						 width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> id=<span style="color: #ff0000;">&quot;grdContato&quot;</span></span>
<span style="color: #000000;">						 width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">						 dataProvider=<span style="color: #ff0000;">&quot;{this.pessoa.contatos}&quot;</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Tipo&quot;</span></span>
<span style="color: #000000;">									   dataField=<span style="color: #ff0000;">&quot;tipo&quot;</span></span>
<span style="color: #000000;">									   width=<span style="color: #ff0000;">&quot;90&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Contato&quot;</span></span>
<span style="color: #000000;">									   dataField=<span style="color: #ff0000;">&quot;contato&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Apagar&quot;</span></span>
<span style="color: #000000;">									   width=<span style="color: #ff0000;">&quot;50&quot;</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> horizontalAlign=<span style="color: #ff0000;">&quot;center&quot;</span><span style="color: #7400FF;">&gt;</span></span>
									<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Button</span> icon=<span style="color: #ff0000;">&quot;@Embed('br/blog/javasimples/agenda/imagens/apagar.png')&quot;</span></span>
<span style="color: #000000;">											   width=<span style="color: #ff0000;">&quot;25&quot;</span></span>
<span style="color: #000000;">											   click=<span style="color: #ff0000;">&quot;outerDocument.apagaContato(data)&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
								<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGridColumn</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/s:TitleWindow</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>O formulário de contatos segue o mesmo padrão do de pessoa: ao clicar no botão salvar é criado um novo Contato, adicionado na lista de contatos da pessoa e então a pessoa é salva novamente para persistir o novo contato no banco (em cascata); para remover um contato nós apenas o removemos da lista de contatos da pessoa e o apagamos do banco. Simples assim! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Para mostrar a tela de contatos, perceba que quando o botão referente a essa função for clicado ele vai chamar a função <em>mostraContatos()</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Abre uma nova janela com os contatos da pessoa selecionada.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> mostraContatos<span style="color: #66cc66;">&#40;</span>obj:<span style="color: #0066CC;">Object</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> pessoa:Pessoa=obj as Pessoa;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>pessoa<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">var</span> formContatos:Contatos=<span style="color: #000000; font-weight: bold;">new</span> Contatos<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		formContatos.<span style="color: #006600;">pessoa</span>=pessoa;
		PopUpManager.<span style="color: #006600;">addPopUp</span><span style="color: #66cc66;">&#40;</span>formContatos, <span style="color: #0066CC;">this</span>, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
		PopUpManager.<span style="color: #006600;">centerPopUp</span><span style="color: #66cc66;">&#40;</span>formContatos<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Criamos o formulário de contatos, passamos a pessoa que vai ter os contatos exibidos para dentro dele e por fim o adicionamos na tela utilizando o <em>PopUpManager</em>.</p>
<p><strong>LAZY LOADING</strong></p>
<p>Mas no fim das contas, como funciona o lazy loading que nós nem vimos acontecer? hehehehe</p>
<p>Repare na grid que mostra os contatos:</p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> id=<span style="color: #ff0000;">&quot;grdContato&quot;</span></span>
<span style="color: #000000;">				 width=<span style="color: #ff0000;">&quot;100%&quot;</span></span>
<span style="color: #000000;">				 dataProvider=<span style="color: #ff0000;">&quot;{this.pessoa.contatos}&quot;</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Tipo&quot;</span></span>
<span style="color: #000000;">							   dataField=<span style="color: #ff0000;">&quot;tipo&quot;</span></span>
<span style="color: #000000;">							   width=<span style="color: #ff0000;">&quot;90&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Contato&quot;</span></span>
<span style="color: #000000;">							   dataField=<span style="color: #ff0000;">&quot;contato&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Apagar&quot;</span></span>
<span style="color: #000000;">							   width=<span style="color: #ff0000;">&quot;50&quot;</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> horizontalAlign=<span style="color: #ff0000;">&quot;center&quot;</span><span style="color: #7400FF;">&gt;</span></span>
							<span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Button</span> icon=<span style="color: #ff0000;">&quot;@Embed('br/blog/javasimples/agenda/imagens/apagar.png')&quot;</span></span>
<span style="color: #000000;">									   width=<span style="color: #ff0000;">&quot;25&quot;</span></span>
<span style="color: #000000;">									   click=<span style="color: #ff0000;">&quot;outerDocument.apagaContato(data)&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
						<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
					<span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Component</span><span style="color: #7400FF;">&gt;</span></span>
				<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:itemRenderer</span><span style="color: #7400FF;">&gt;</span></span>
			<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGridColumn</span><span style="color: #7400FF;">&gt;</span></span>
		<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
	<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>O <em>dataProvider</em> da grid é o atributo <em><strong>contatos</strong></em> do objeto <em><strong>pessoa</strong></em>. Quando o formulário está sendo carregado e a grid executa o primeiro get no atributo o dpHibernate já se encarrega de fazer uma chamada remota para carregar os contatos.</p>
<p>Quando utilizamos atributos que irão ser carregados preguiçosamente (lazy loading) no MXML (como na grid) não precisamos nos preocupar com absolutamente nada, o FLEX e o dpHibernate se encarregam de tudo. Mas e quando precisamos utilizar tais atributos no AS (em uma função)?</p>
<p>Todo objeto que sofre lazy loading dispara o evento <em>LazyLoadEvent</em>. Tal evento possui 3 tipos:</p>
<p><strong><em>LazyLoadEvent.pending</em></strong>: é disparado antes de fazer a chamada remota que carregará o objeto;</p>
<p><strong><em>LazyLoadEvent.failed</em></strong>: é disparado quando ocorre uma falha no processo de carregamento do objeto;</p>
<p><strong><em>LazyLoadEvent.complete</em></strong>: é disparado quando o carregamento foi concluído, ou seja, a chamada remota retornou com os dados e o objeto já foi atualizado com tais dados.</p>
<p>Então vamos fazer uma pequena alteração na função que abre o formulário de contatos para ver se isso verdade:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Abre uma nova janela com os contatos da pessoa selecionada.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> mostraContatos<span style="color: #66cc66;">&#40;</span>obj:<span style="color: #0066CC;">Object</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> pessoa:Pessoa=obj as Pessoa;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>pessoa<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">var</span> formContatos:Contatos=<span style="color: #000000; font-weight: bold;">new</span> Contatos<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>pessoa.<span style="color: #006600;">contatos</span>.<span style="color: #0066CC;">length</span> <span style="color: #66cc66;">&amp;</span>gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
			pessoa.<span style="color: #006600;">contatos</span>.<span style="color: #006600;">getItemAt</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>LazyLoadEvent.<span style="color: #006600;">complete</span>, formContatos.<span style="color: #006600;">contatosCarregados</span><span style="color: #66cc66;">&#41;</span>;
		formContatos.<span style="color: #006600;">pessoa</span>=pessoa;
		PopUpManager.<span style="color: #006600;">addPopUp</span><span style="color: #66cc66;">&#40;</span>formContatos, <span style="color: #0066CC;">this</span>, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
		PopUpManager.<span style="color: #006600;">centerPopUp</span><span style="color: #66cc66;">&#40;</span>formContatos<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Tudo bem, concordo que não é um código muito bonito&#8230; hehehe Mas como vimos a pouco, quem dispara o evento é o <strong>objeto que vai ser carregado preguiçosamente</strong>, sendo assim precisamos acessar algum desses objetos para poder colocar um listener nele. Devemos sempre ter certeza de que existe pelo menos um contato a ser carregado para poder acessá-lo e colocar um listener nele pois caso não fizéssemos a verificação antes e tentássemos abrir o formulário de contatos para uma pessoa que não tem nenhum contato nós iriamos receber um erro em tempo de execução.</p>
<p><strong>Devemos sempre tomar muito cuidado ao programar as funções em AS, qualquer errinho vai estourar uma mensagem não muito agradável para o usuário final.</strong></p>
<p>Dando continuidade, o listener que adicionamos foi para chamar a função <em>contatosCarregados() </em>do formulário de contatos, vamos a ela então:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Mostra uma mensagem avisando que os contatos foram carregados.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> contatosCarregados<span style="color: #66cc66;">&#40;</span>event:LazyLoadEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	Alert.<span style="color: #0066CC;">show</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;A lista de contatos foi carregada com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Com isso, a primeira vez que abrirmos o formulário de contatos de uma pessoa que possua pelo menos um contato a ser carregado iremos receber a mensagem:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/08/lista_carregada.png" target="_blank"><img class="aligncenter size-medium wp-image-579" title="lista_carregada" src="http://www.javasimples.com.br/wp-content/uploads/2011/08/lista_carregada-300x271.png" alt="" width="300" height="271" /></a></p>
<p><strong>CARREGAMENTO EM LOTES (BATCH LOADING)</strong></p>
<p>Uma última coisa (e não menos importante) para fecharmos esse post: carregamento em lotes.</p>
<p>Sem muita teoria, vou demonstrar com exemplos pois vai ser muito mais facil de entender né. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Eu criei uma pessoa e adicionei 3 contatos a ela, na próxima vez que eu entrar no sistema e abrir o formulário de contatos dela e seus contatos forem carregados reparem na saída impressa no console (ou arquivos de log) do tomcat:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">{operation})****************loadBean
{deserialize} 0
Hibernate:
    select
        contato0_.ID as ID0_0_,
        contato0_.CONTATO as CONTATO0_0_,
        contato0_.ID_PESSOA as ID4_0_0_,
        contato0_.TIPO as TIPO0_0_
    from
        CONTATO contato0_
    where
        contato0_.ID=?
{invoke} 10
{serialize} 1
{operation})****************loadBean
{deserialize} 1
Hibernate:
    select
        contato0_.ID as ID0_0_,
        contato0_.CONTATO as CONTATO0_0_,
        contato0_.ID_PESSOA as ID4_0_0_,
        contato0_.TIPO as TIPO0_0_
    from
        CONTATO contato0_
    where
        contato0_.ID=?
{invoke} 15
{serialize} 0
{operation})****************loadBean
{deserialize} 0
Hibernate:
    select
        contato0_.ID as ID0_0_,
        contato0_.CONTATO as CONTATO0_0_,
        contato0_.ID_PESSOA as ID4_0_0_,
        contato0_.TIPO as TIPO0_0_
    from
        CONTATO contato0_
    where
        contato0_.ID=?
{invoke} 1
{serialize} 1</pre></div></div>

<p>Cada vez que o dpHibernate imprime <strong>{operation})*********nome_da_operacao</strong> quer dizer que chegou uma chamada remota! Repare que até tem quanto tempo levou para deserializar a chamada e para serializar a resposta.</p>
<p>Quer dizer, 1 chamada remota para carregar cada contato&#8230; Vamos e venhamos, isso não é muito eficiente né.</p>
<p>Para suprir esse problema o dpHibernate consegue trabalhar com lotes de requisições (explicados detalhadamente pelo criador <a title="Batch Loading Proxies in dpHibernate" href="http://martypitt.wordpress.com/2010/07/07/batch-loading-proxies-in-dphibernate/" target="_blank">neste post</a>), ou seja, ao invés de uma requisição para cada contato, todas são agrupadas em um lote e são enviadas para o servidor em apenas uma chamada remota. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Para habilitar isso precisamos de mais uns ajustes nas configurações (coisa rápida, prometo!).</p>
<p>Vamos adicionar um novo bean no contexto do <em>DispatcherServlet</em> do <strong>Spring BlazeDS Integration</strong> (arquivo <em>WEB-INF\spring\flex-config.xml</em>):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;proxyBatchLoader&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.dphibernate.services.ProxyBatchLoader&quot;</span> <span style="color: #000066;">autowire</span>=<span style="color: #ff0000;">&quot;constructor&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>E na função <em>onApplicationComplete()</em> onde definimos o service padrão para o CRUD do dpHibernate vamos indicar que ele deve começar a enviar as requisições em lotes:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Inicializações gerais.
 */</span>
protected <span style="color: #000000; font-weight: bold;">function</span> onApplicationComplete<span style="color: #66cc66;">&#40;</span>event:FlexEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> remoteObject:HibernateRemoteObject=<span style="color: #000000; font-weight: bold;">new</span> HibernateRemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;dataAccessService&quot;</span><span style="color: #66cc66;">&#41;</span>;
	remoteObject.<span style="color: #006600;">bufferProxyLoadRequests</span>=<span style="color: #000000; font-weight: bold;">true</span>;
	HibernateManaged.<span style="color: #006600;">defaultHibernateService</span>=remoteObject;
	<span style="color: #0066CC;">this</span>.<span style="color: #006600;">getAgenda</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>E pronto! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  Ao rodar a aplicação novamente, abrir o formulário de contatos da pessoa que possui 3 contatos e observar o console (ou log) do tomcat veremos a seguinte saída:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">{operation})****************loadProxyBatch
{deserialize} 6
Hibernate:
    select
        this_.ID as ID0_0_,
        this_.CONTATO as CONTATO0_0_,
        this_.ID_PESSOA as ID4_0_0_,
        this_.TIPO as TIPO0_0_
    from
        CONTATO this_
    where
        this_.ID in (
            ?, ?, ?
        )
{invoke} 219
{serialize} 5</pre></div></div>

<p>Apenas uma requisição que já carregou os 3 contatos!</p>
<p>Agora sim a nossa aplicação está 100%! Bonita, funcional e eficiente! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Os projetos completos (incluindo as biliotecas) podem ser baixados <a title="Projetos AgendaJ e AgendaF" href="http://dl.dropbox.com/u/4918828/JavaSimples/Spring_Flex_Parte_3_Final.rar">aqui</a> (20MB).</p>
<p><strong>CONCLUSÃO</strong></p>
<p>É isso ai pessoal, o post acabou ficando um pouco longo mas creio que se você leu até aqui não ficou decepcionado com o tempo gasto, certo? hehehe <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Um ponto que vale a pena ser comentado é em relação ao nosso Service e nosso DAO de Pessoa, depois de implantar o dpHibernate no nosso projeto vamos ver como eles ficaram:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos de um serviço para {@link Pessoa}.
 *
 * @author Felipe Saab
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> PessoaService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Recupera todas as pessoas da agenda.
	 *
	 * @return Todos as pessoas
	 */</span>
	<span style="color: #003399;">List</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos necessários para o DAO de Pessoa.
 *
 * @author Felipe Saab
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> PessoaDao <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Recupera todas as pessoas da agenda.
	 *
	 * @return Todos as pessoas
	 */</span>
	<span style="color: #003399;">List</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como ficou simples! Sem os métodos referentes ao CRUD (tudo bem, ainda tem um select ai.. dá um desconto poxa.. heheh) o Service e o DAO passam a ter somente a regra de negócio referente a entidade pela qual são responsáveis. A aplicação acaba se tornando mais legível! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Olhando agora para a nossa aplicação e tudo o que fizemos nela desde a Parte 1 dessa série podemos ver que utilizamos vários frameworks para aumentar a nossa produtividade: Spring, Hibernate, Spring BlazeDS Integration e dpHibernate. Com isso conseguimos construir uma aplicação como esta agenda em poucas horas (chegaria em horas mesmo? hehehe), desde o banco de dados até a interface agradável para o usuário final.</p>
<p>O dpHibernate é um framework poderosíssimo (li em blogs que já foi utilizado para projetos de grande porte) e open source! Caso esteja curioso sobre como ele funciona basta fazer checkout no repositório SVN na página do projeto (o que eu aconselho fortemente) e fuçar&#8230; muito legal mesmo!</p>
<p>Espero que tenha gostado deste post, todos os feedbacks são importantes, não deixe de comentar por favor. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>PS: Caso esteja desenvolvendo um projeto com o dpHibernate sinta-se a vontade para me procurar caso esteja passando por alguns problemas, já passei por vários e você não precisa passar por eles também. =]</p>
<p>[]s e até a próxima,<br />
Saab.</p>
<p><strong>REFERÊNCIAS</strong></p>
<p>[1] <a href="http://www.axelscript.com/2008/02/29/using-the-itemrenderer-with-a-datagrid-in-flex/">Using the ItemRenderer with a DataGrid</a></p>
<p>[2] <a href="http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=serialize_data_3.html">Explicitly mapping ActionScript and Java objects</a></p>
<p>[3] <a href="http://code.google.com/p/dphibernate/wiki/SetupAndConfigurationV2">Steps for getting going with dpHibernate</a></p>
<p>[4] <a href="http://code.google.com/p/dphibernate/issues/detail?id=64">Serialization issue with using primitive type long</a></p>
<p>[5] <a href="http://martypitt.wordpress.com/2010/07/07/batch-loading-proxies-in-dphibernate/">Batch loading proxies in dpHibernate</a></p>
<div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 2283px; width: 1px; height: 1px; overflow: hidden;">&lt;?xml version=&#8221;1.0&#8243; encoding=&#8221;UTF-8&#8243;?&gt;<br />
&lt;web-app xmlns:xsi=&#8221;http://www.w3.org/2001/XMLSchema-instance&#8221;<br />
xmlns=&#8221;http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=&#8221;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;<br />
xsi:schemaLocation=&#8221;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;<br />
id=&#8221;WebApp_ID&#8221; version=&#8221;2.5&#8243;&gt;&lt;!&#8211; Listener responsável por iniciar o container do Spring &#8211;&gt;<br />
&lt;listener&gt;<br />
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;<br />
&lt;/listener&gt;</p>
<p>&lt;!&#8211; Localização do arquivo de configuração para o listener configurar o container &#8211;&gt;<br />
&lt;context-param&gt;<br />
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br />
&lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt;<br />
&lt;/context-param&gt;</p>
<p>&lt;!&#8211; Filtro para manter sempre &#8211; e apenas! &#8211; uma sessão do Hibernate aberta &#8211;&gt;<br />
&lt;filter&gt;<br />
&lt;filter-name&gt;openSessionInViewFilter&lt;/filter-name&gt;<br />
&lt;filter-class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&gt;<br />
&lt;/filter&gt;</p>
<p>&lt;!&#8211; DispatcherServlet para o Spring BlazeDS Integration &#8211;&gt;<br />
&lt;servlet&gt;<br />
&lt;servlet-name&gt;springMessageBroker&lt;/servlet-name&gt;<br />
&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;<br />
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br />
&lt;/servlet&gt;</p>
<p>&lt;!&#8211; Mappings &#8211;&gt;</p>
<p>&lt;filter-mapping&gt;<br />
&lt;filter-name&gt;openSessionInViewFilter&lt;/filter-name&gt;<br />
&lt;url-pattern&gt;/*&lt;/url-pattern&gt;<br />
&lt;/filter-mapping&gt;</p>
<p>&lt;servlet-mapping&gt;<br />
&lt;servlet-name&gt;springMessageBroker&lt;/servlet-name&gt;<br />
&lt;url-pattern&gt;/messagebroker/*&lt;/url-pattern&gt;<br />
&lt;/servlet-mapping&gt;<br />
&lt;/web-app&gt;</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/flex/java-flex-parte-3-spring-blazeds-integration-dphibernate/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Java + FLEX Parte 2 -&gt; Spring BlazeDS Integration + Hibernate</title>
		<link>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-2</link>
		<comments>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-2#comments</comments>
		<pubDate>Thu, 23 Jun 2011 21:53:58 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[FLEX]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[blazeds]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[integração]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[refatoração]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=438</guid>
		<description><![CDATA[Fala pessoal, finalmente a parte 2 do tutorial da nossa integração Java + FLEX! CONSIDERAÇÕES INICIAIS Caso você não tenha visto a Parte 1 do tutorial, por favor, veja ou baixe a aplicação pois a refatoração será feita em cima do projeto desenvolvido no tutorial anterior. INTRODUÇÃO Até agora o que temos é uma aplicação [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/java_flex_parte_211.png"></a><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/java_flex_parte_21.png"></a><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/java_flex_parte_212.png" target="_blank"><img class="aligncenter size-full wp-image-448" title="java_flex_parte_2(1)" src="http://www.javasimples.com.br/wp-content/uploads/2011/06/java_flex_parte_212.png" alt="" width="563" height="191" /></a></p>
<p>Fala pessoal, finalmente a parte 2 do tutorial da nossa integração Java + FLEX! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>CONSIDERAÇÕES INICIAIS</strong></p>
<p>Caso você não tenha visto a <a title="Java (Spring &amp; Hibernate) + FLEX (Flash Builder 4) – Parte 1" href="../spring-2/java-spring-hibernate-flex-flash-builder-4-parte-1/" target="_blank">Parte 1</a> do tutorial, por favor, veja ou baixe a aplicação pois a refatoração  será feita em cima do projeto desenvolvido no tutorial anterior.</p>
<p><strong>INTRODUÇÃO</strong></p>
<p>Até agora o que temos é uma  aplicação com o objetivo de ser uma Agenda de Contatos, porém os  contatos estão ficando apenas em memória (uma lista estática na classe  ContatoService.java), ao parar o servidor e rodá-lo novamente os  contatos anteriormente salvos sumiram.. Ok, para evitar isso vamos  persistir os contatos em um banco de dados, e para facilitar ainda mais a  nossa vida vamos utilizar o Hibernate para nem nos preocuparmos com  SQL, mecher apenas com as classes.</p>
<p>OBS: Por favor não me entenda  errado, saber SQL é extremamente  importante!! Mesmo utilizando o  Hibernate as vezes precisamos construir  querys utilizando HQL ou mesmo  SQL, mas como nossa aplicação é  extremamente simples nós podemos deixar  isso de lado e utilizar todas as  facilidades que o Hibernate provê.</p>
<p>E tem também o Spring! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  Ele nos será útil por dois fatores:</p>
<p>Injeção  de Dependência: vamos utilizar interfaces e anotações para o Spring  injetar os beans que precisamos em cada classe. Por consequência  melhorar muito o projeto (design) da nossa aplicação pois as classes  ficarão desacopladas (pois utilizaremos as interfaces). Conforme formos  escrevendo o código isso ficará mais claro. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Integração com o  BlazeDS: vamos utilizar um framework que a SpringSource criou para a  integração do Spring com o BlazeDS para não precisarmos de muitas  configurações e para termos possibilidade de aproveitar todas as  funcionalidades do Spring como segurança e mensagens por exemplo. Para  entender melhor sobre este projeto recomendo a leitura da referência  [1].</p>
<p>Vamos fazer as coisas por partes então: primeiro vamos  adicionar o Spring ao nosso projeto e depois adicionaremos o Hibernate  pois ele vai ser um bean gerenciado pelo Spring também.</p>
<p><span id="more-438"></span></p>
<p><strong>DOWNLOADS</strong></p>
<p><a title="Download do Spring Framework" href="http://www.springsource.com/download/community" target="_blank">Spring Framework</a>: Iremos precisar do <a title="Spring Framework" href="http://www.springsource.com/download/community?project=Spring%20Framework" target="_blank">Spring Framework</a> (utilizarei o 3.1.0 M2) em si e de um outro projeto da SpringSource chamado <a title="Spring BlazeDS Integration" href="http://www.springsource.com/download/community?project=Spring%20BlazeDS%20Integration" target="_blank">Spring BlazeDS Integration</a> projetado para facilitar a comunicação do Spring com o FLEX.</p>
<p><a title="Hibernate" href="http://sourceforge.net/projects/hibernate/files/hibernate3/">Hibernate</a>: No momento em que estou escrevendo este post a última versão é a <a title="Hibernate 3.6.5" href="http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.5.Final/" target="_blank">3.6.5</a>.</p>
<p><strong>MÃO NA MASSA: SPRING<br />
</strong></p>
<p>Vamos começar a escrever códigos então! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Hoje o serviço que o FLEX acessa para recuperar/adicionar os contatos é a classe ContatoService que tem todos os métodos já implementados. Vamos criar uma interface para este serviço para tornar a nossa aplicação mais desacoplada (para mais informação sobre interfaces  e suas vantagens leia <a title="Spring Framework Parte 1 -&gt; Dependency Injection" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-1-dependency-injection/">este post</a>).</p>
<p>Vamos mudar o nome da classe <em>ContatoService.java</em> para <em>ContatoServiceImpl.java</em> e mudar ela de pacote também: vamos criar um novo pacote e movê-la para ele: <em>br.blog.javasimples.agenda.service.impl</em>.</p>
<p>Agora que a classe já está com o novo nome podemos criar a interface com o nome antigo (<em>ContatoService.java</em>) no pacote <em>br.blog.javasimples.agenda.service</em> (apenas por questões de padrão de nomenclatura). Sendo assim temos a seguinte estrutura:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/contatoserviceimpl.png" target="_blank"><img class="aligncenter size-full wp-image-459" title="contatoserviceimpl" src="http://www.javasimples.com.br/wp-content/uploads/2011/06/contatoserviceimpl.png" alt="" width="312" height="297" /></a></p>
<p>A interface ContatoService apenas vai definir os métodos que um serviço para contatos deve ter:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos de um serviço para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> ContatoService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Salva um contato.
	 *
	 * @param contato - {@link Contato} a ser salvo
	 */</span>
	<span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Recupera todos os contatos.
	 *
	 * @return Todos os contatos
	 */</span>
	List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E a classe ContatoServiceImpl.java agora deve implementar a interface:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Serviço para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContatoServiceImpl <span style="color: #000000; font-weight: bold;">implements</span> ContatoService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@link List Lista} que guarda todos os contatos.
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> agenda <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		ContatoServiceImpl.<span style="color: #006633;">agenda</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Contato adicionado: &quot;</span> <span style="color: #339933;">+</span> contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> ContatoServiceImpl.<span style="color: #006633;">agenda</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Legal, agora que o serviço já virou uma interface e tem sua implementação vamos adicionar as bibliotecas do Spring no nosso projeto.</p>
<p>As bibliotecas que precisamos estão em:<em> {pasta de download do spring}/dist</em> e <em>{pasta de donwload do spring blazeds integration}/dist</em>.</p>
<p>Fiz um <a title="Bibliotecas para o Spring" href="http://dl.dropbox.com/u/4918828/JavaSimples/Bibliotecas%20para%20o%20Spring.rar">pacote com algumas bibliotecas</a> que o Spring utiliza e irão gerar erro caso não estejam no projeto. Adicione essas bibliotecas no classpath também.</p>
<p>Para adicionar as bibliotecas basta colar (CTRL + V) elas na pasta <em>WebContent/WEB-INF/lib</em> do projeto ContatosJ:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/libs_spring.png" target="_blank"><img class="aligncenter size-medium wp-image-456" title="libs_spring" src="http://www.javasimples.com.br/wp-content/uploads/2011/06/libs_spring-164x300.png" alt="" width="164" height="300" /></a></p>
<p>Vamos agora começar a mecher em algumas configurações:</p>
<p><em>WebContent/WEB-INF/web.xml</em></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;web-app</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/j2ee&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;2.4&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>spring<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.servlet.DispatcherServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/WEB-INF/applicationContext.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>spring<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/messagebroker/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/web-app<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Antes nós tinhamos o MessageBrokerServlet definido no nosso arquivo, porém com o projeto de integração entre BlazeDS e Spring nós não precisamos mais ter isso tão explícito, o próprio projeto (Spring BlazeDS Integration) se responsabiliza por criar o MessageBroker e fazer todas as configurações internamente.</p>
<p>Porém o pessoal que criou o projeto utilizou o <a title="Spring Framework Parte 5 -&gt; Spring Web MVC" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-5-spring-web-mvc/" target="_blank">Spring Web MVC</a> internamente (aceitável né&#8230; hehehe), sendo assim, tudo o que precisamos fazer é criar um DispatcherServlet (controlador responsável por todas as requisições que chegam para o Spring Web MVC) e mapear todas as requisições que chegarem para o MessageBroker (/messageBroker/*) para ele, ou seja, toda vez que o FLEX enviar uma requisição para a nossa aplicação (a URL vai ser +/- assim: http://localhost:8080/AgendaJ/messageBroker/my-amf/&#8230;) ela vai ser encaminhada para o DispatcherServlet e ele por sua vez vai encaminhar para a classe que deve receber e tratar a requisição.</p>
<p>Vamos criar o arquivo de configuração do Spring em WebContent/WEB-INF/applicationContext.xml (pois informamos este caminho no DispatcherServlet definido no web.xml).</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/appContext.png" target="_blank"><img class="aligncenter size-medium wp-image-466" title="appContext" src="http://www.javasimples.com.br/wp-content/uploads/2011/06/appContext-292x300.png" alt="" width="292" height="300" /></a></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">xmlns:p</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/p&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">xmlns:flex</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/flex&quot;</span></span>
<span style="color: #009900;">       <span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context/spring-context.xsd</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex/spring-flex-1.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Cria o MessageBroker com as configurações padrão --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;flex:message-broker</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Habilita a injeção de dependência através de anotações --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Faz com que os Services sejam beans gerenciados pelo container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.service.impl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Neste pequeno arquivo de configuração nós estamos definindo tudo que precisamos para fazer o Spring conversar com FLEX como se fosse por mágica! hehehe</p>
<p>Com a tag <em>&lt;flex:message-broker /&gt;</em> nós estamos pedindo para o Spring BlazeDS Integration criar o MessageBroker (a classe que vai receber as requisições através do DispatcherServlet que configuramos no web.xml).</p>
<p>A tag<em> &lt;context:annotation-config /&gt;</em> habilita a injeção de dependência através de anotações. Para que o Spring BlazeDS Integration consiga fazer com que a comunicação aconteça sem que nós fiquemos configurando muita coisa os Serviços que vão receber as chamadas remotas devem ser gerenciados pelo container do Spring. Para isso nós poderíamos declarar os beans de serviço no applicationContext.xml através da tag<em> &lt;bean id=&#8221;contatoService&#8221; class=&#8221;br.blog.javasimples.service.impl.ContatoServiceImpl&#8221; /&gt; </em>porém para cada novo serviço deveríamos fazer o mesmo. Para evitar isso utilizaremos a anotação <em>@Service</em> nas classes para fazer com que o Spring possa gerenciá-las. É equivalente à utilização da tag <em>&lt;bean&gt;</em>. Se você ainda não entendeu continue lendo que já já vai ficar claro. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>E a tag<em> &lt;context:component-scan /&gt;</em> fala para o container do Spring procurar no pacote br.blog.javasimples.agenda.service.impl por classes que estejam anotadas com @Service e com outras anotações que ele conhece para gerenciá-las, ou seja, para poder fazer injeção de dependência e para utilizá-las para comunicar com o FLEX.</p>
<p>Para terminarmos a parte de configuração do Spring vamos voltar e mecher na implementação do serviço de Contato adicionando algumas anotações nele:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Serviço para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
@Service
@RemotingDestination<span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;contatoService&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContatoServiceImpl <span style="color: #000000; font-weight: bold;">implements</span> ContatoService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@link List Lista} que guarda todos os contatos.
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> agenda <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		ContatoServiceImpl.<span style="color: #006633;">agenda</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Contato adicionado: &quot;</span> <span style="color: #339933;">+</span> contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> ContatoServiceImpl.<span style="color: #006633;">agenda</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A anotação<em> @Service </em>diz que a classe ContatoServiceImpl vai ser gerenciada pelo Spring, ou seja, ela vai estar presente no container do Spring, consequentemente ela vai conseguir ser acessada por injeção de dependência, e pelo Spring BlazeDS Integration (e qualquer outro lugar que precise dessa classe através do Spring).</p>
<p>E a anotação<em> @RemotingDestination</em> informa qual o id devemos utilizar no RemoteObject do FLEX para chamar os métodos desta classe. Simples assim!!! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Lembra que criamos uma tag <em>&lt;destination&gt; </em>no arquivo WebContent/WEB-INF/flex/remoting-config.xml informando o id e a classe? Agora não precisa mais, só essa anotação já resolve todos os problemas, faz com que o Spring BlazeDS Integration faça tudo sozinho por trás.</p>
<p>Com o Spring BrazeDS Integration tomando conta de criar e gerenciar todas as configurações que vamos precisar para a comunicação Java &lt;-&gt; FLEX podemos &#8220;fazer um limpa&#8221; nos arquivos de configuração do BlazeDS que nós não vamos utilizar ou que o Spring irá criar sozinho. Podemos apagar os arquivos <strong>WebContent/WEB-INF/flex/remoting-config.xml, WebContent/WEB-INF/flex/messaging-config.xml e WebContent/WEB-INF/flex/proxy-config.xml</strong>:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/flex-config.png"><img src="http://www.javasimples.com.br/wp-content/uploads/2011/06/flex-config.png" alt="" title="flex config" width="288" height="259" class="aligncenter size-full wp-image-505" /></a></p>
<p>Agora vamos ajeitar o arquivo <strong>WebContent/WEB-INF/flex/services-config.xml</strong> para não referenciar mais os arquivos excluídos:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;services-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;default-channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;my-amf&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/default-channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;login-command</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.security.TomcatLoginCommand&quot;</span></span>
<span style="color: #009900;">			<span style="color: #000066;">server</span>=<span style="color: #ff0000;">&quot;Tomcat&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel-definition</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;my-amf&quot;</span></span>
<span style="color: #009900;">			<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;mx.messaging.channels.AMFChannel&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span></span>
<span style="color: #009900;">				<span style="color: #000066;">url</span>=<span style="color: #ff0000;">&quot;http://{server.name}:{server.port}/{context.root}/messagebroker/amf&quot;</span></span>
<span style="color: #009900;">				<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.endpoints.AMFEndpoint&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channel-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;logging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;target</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.log.ConsoleTarget&quot;</span> <span style="color: #000066;">level</span>=<span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prefix<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>[BlazeDS] <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prefix<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeDate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeDate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeTime<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeTime<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeCategory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeCategory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Endpoint.*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Service.*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Configuration<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/target<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/logging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;redeploy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>20<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/flex/services-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;touch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/web.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/touch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/redeploy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/services-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>A grande alteração nesse arquivo foi na tag &lt;services&gt; onde removemos as referências aos arquivos que acabamos de excluir e indicamos para o BlazeDS que o canal padrão para a comunicação é o canal <strong>my-amf</strong>, ou seja, todas as requisições que chegarem para o message-broker e não tiverem um canal em específico irão ser enviados para o canal <strong>my-amf</strong>.</p>
<p>OBS: também foram removidas as referências dos arquivos removidos da tag &lt;redeploy&gt;.</p>
<p>E com isso terminamos a configuração do Spring! Que maravilha não?!?! Valeu SpringSource por fazer esse projetinho show de bola! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>ADICIONANDO O HIBERNATE</strong></p>
<p>Uma vez que o Spring está configurado vamos para a persistência dos dados com o Hibernate.</p>
<p>Primeiro de tudo vamos criar um banco de dados para a nossa aplicação:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> contato <span style="color: #66cc66;">&#40;</span>
	id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">11</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">,</span>
	nome <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">50</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #66cc66;">,</span>
	telefone <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">14</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #66cc66;">,</span>
	email <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">50</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #66cc66;">,</span>
	<span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span> id <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE <span style="color: #66cc66;">=</span> innodb <span style="color: #993333; font-weight: bold;">CHARACTER</span> <span style="color: #993333; font-weight: bold;">SET</span> utf8 <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci;</pre></div></div>

<p>Ok, agora precisamos das bibliotecas do Hibernate no classpath da nossa aplicação. Vamos adicionar as bibliotecas:<br />
{pasta download hibernate}/hibernate3.jar<br />
{pasta download hibernate}/lib/jpa<br />
{pasta download hibernate}/lib/required<br />
{pasta download hibernate}/lib/bytecode/javassist</p>
<p>E também precisamos da biblioteca que contém o driver do banco de dados que estamos utilizando (no meu caso a do MySQL).</p>
<p>Agora já podemos realizar o mapeamento objeto relacional da nossa classe<em> Contato.java</em> para a tabela Contato do banco de dados (eu gosto de mapear utilizando anotações, mas não tem problema nenhum utilizar xml):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Classe que representa um Contato da agenda.
 *
 * @author Felipe Saab
 */</span>
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CONTATO&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Serializable</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>1549466344815889020L<span style="color: #339933;">;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>strategy<span style="color: #339933;">=</span>GenerationType.<span style="color: #006633;">AUTO</span><span style="color: #009900;">&#41;</span>
	@Column<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;ID&quot;</span>, length<span style="color: #339933;">=</span><span style="color: #cc66cc;">11</span>, nullable<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Long</span> id<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;NOME&quot;</span>, length<span style="color: #339933;">=</span><span style="color: #cc66cc;">50</span>, nullable<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;TELEFONE&quot;</span>, length<span style="color: #339933;">=</span><span style="color: #cc66cc;">14</span>, nullable<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> telefone<span style="color: #339933;">;</span>
&nbsp;
	@Column<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;EMAIL&quot;</span>, length<span style="color: #339933;">=</span><span style="color: #cc66cc;">50</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> email<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Long</span> getId<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> id<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setId<span style="color: #009900;">&#40;</span><span style="color: #003399;">Long</span> id<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">id</span> <span style="color: #339933;">=</span> id<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getNome<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setNome<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nome</span> <span style="color: #339933;">=</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getTelefone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> telefone<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setTelefone<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> telefone<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">telefone</span> <span style="color: #339933;">=</span> telefone<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getEmail<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> email<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setEmail<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> email<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">email</span> <span style="color: #339933;">=</span> email<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		StringBuilder sb <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getTelefone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getEmail</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Foi adicionado o atributo id para representar a chave primária do contato.</p>
<p>Como também existe uma classe Contato no FLEX precisamos atualizá-la:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package br.<span style="color: #006600;">blog</span>.<span style="color: #006600;">javasimples</span>.<span style="color: #006600;">agenda</span>.<span style="color: #006600;">model</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span>
	<span style="color: #66cc66;">&#91;</span>RemoteClass<span style="color: #66cc66;">&#40;</span>alias=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.model.Contato&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> id:<span style="color: #0066CC;">Number</span>;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> nome:<span style="color: #0066CC;">String</span>;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> telefone:<span style="color: #0066CC;">String</span>;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> email:<span style="color: #0066CC;">String</span>;
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Vamos utilizar agora um padrão de projeto (design pattern) chamado <strong>DAO</strong> (Data Access Object): tal padrão visa centralizar o acesso aos dados em um único objeto, ou seja, sempre que precisarmos gravar/recuperar algo do banco de dados vamos utilizar os métodos desse objeto.</p>
<p>Do mesmo jeito que fizemos a interface <em>ContatoService </em>é interessante fazer a <em>ContatoDao</em>. Seguindo o padrão de nomenclarura dos pacotes vamos criá-la no pacote <em>br.blog.javasimples.agenda.dao</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Interface que define os métodos de um DAO para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> ContatoDao <span style="color: #009900;">&#123;</span>
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Salva um contato.
	 *
	 * @param contato - {@link Contato} a ser salvo
	 */</span>
	<span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Recupera todos os contatos.
	 *
	 * @return Todos os contatos
	 */</span>
	List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Foram definidos os métodos que já estamos utilizando em <em>ContatoService </em>para acessar os dados para depois que o DAO estiver pronto nós apenas delegarmos a chamada do Service para DAO. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Vamos para a implementação então &#8211; sempre seguindo o padrão de nomenclatura dos pacotes: <em>br.blog.javasimples.agenda.dao.impl</em>.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/06/daoImpl.png"><img class="aligncenter size-medium wp-image-482" title="daoImpl" src="http://www.javasimples.com.br/wp-content/uploads/2011/06/daoImpl-279x300.png" alt="" width="279" height="300" /></a></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * DAO para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
@<span style="color: #003399;">Repository</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContatoDaoImpl <span style="color: #000000; font-weight: bold;">extends</span> HibernateDaoSupport <span style="color: #000000; font-weight: bold;">implements</span> ContatoDao <span style="color: #009900;">&#123;</span>
&nbsp;
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span>SessionFactory sessionFactory<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">setSessionFactory</span><span style="color: #009900;">&#40;</span>sessionFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getHibernateTemplate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">save</span><span style="color: #009900;">&#40;</span>contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getHibernateTemplate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">loadAll</span><span style="color: #009900;">&#40;</span>Contato.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A anotação <em>@Repository</em> funciona como a anotação <em>@Service</em>, ou seja, o container do Spring vai conseguir gerenciá-la dinamicamente por causa dessa anotação. Essa anotação também é utilizada para alguns tratamentos específicos para a camada de persistência de dados, mas não vem ao caso agora. heheh</p>
<p>O método <em>init(SessionFactory)</em> que é executado internamente após a classe ser instanciada  serve para configurar a classe pai (<em>HibernateDaoSupport</em>) setando a SessionFactory nele. Esse método possui a anotação<em> @Autowired </em>pois antes dele ser executado o Spring vai injetar o atributo sessionFactory para nós (a classe estando anotada com<em> @Repository </em>demonstra que ela pode estar no container e o Spring vai conseguir injetar as dependências).</p>
<p>Porém essa nova classe precisa de mais algumas configurações no arquivo de configuração do Spring (<em>applicationContext.xml</em>) para poder funcionar:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:p</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/p&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:context</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:flex</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/flex&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/context/spring-context.xsd</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex</span>
<span style="color: #009900;">                           http://www.springframework.org/schema/flex/spring-flex-1.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Cria o MessageBroker com as configurações padrão --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;flex:message-broker</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Habilita a injeção de dependência através de anotações --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:annotation-config</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Faz com que os Services sejam beans gerenciados pelo container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.service.impl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Faz com que os DAOs sejam beans gerenciados pelo container do Spring --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.dao.impl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- DataSource --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;driverClassName&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.mysql.jdbc.Driver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://localhost:3306/javasimples_agenda<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;username&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>usuario<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>senha<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Hibernate SessionFactory --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ref</span> <span style="color: #000066;">local</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #808080; font-style: italic;">&lt;!-- Carrega todos os Beans --&gt;</span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;packagesToScan&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.blog.javasimples.agenda.model<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
		<span style="color: #808080; font-style: italic;">&lt;!-- Propriedades do Hibernate --&gt;</span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;hibernateProperties&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.dialect&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>org.hibernate.dialect.MySQL5InnoDBDialect<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.show_sql&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;hibernate.format_sql&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Adicionamos uma nova tag &lt;context:component-scan&gt; informando que o pacote onde vão estar os DAOs também deve ser gerenciado pelo Spring, definimos um DataSource (para saber mais leia <a title="Spring Framework Parte 3 -&gt; Java Database Connectivity (JDBC)" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-3-java-database-connectivity-jdbc/">este post</a>) e definimos a <em>SessionFactory </em>(para saber mais leia <a title="Spring Framework Parte 4 -&gt; Integração com o Hibernate" href="http://www.javasimples.com.br/spring-2/spring-framework-parte-4-integracao-com-o-hibernate/">este post</a>) que vai ser injetada no método <em>init(SessionFactory)</em> da classe <em>ContatoDaoImpl</em>.</p>
<p>Uma vez que o DAO está criado e configurado corretamente precisamos mudar o <em>ContatoServiceImpl </em>para utilizá-lo ao invés da lista estática que utilizava antes:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Serviço para {@link Contato}.
 *
 * @author Felipe Saab
 */</span>
@Service
@RemotingDestination<span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;contatoService&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContatoServiceImpl <span style="color: #000000; font-weight: bold;">implements</span> ContatoService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * DAO
	 */</span>
	@Autowired
	<span style="color: #000000; font-weight: bold;">private</span> ContatoDao contatoDao<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">contatoDao</span>.<span style="color: #006633;">salvar</span><span style="color: #009900;">&#40;</span>contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Contato adicionado: &quot;</span> <span style="color: #339933;">+</span> contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * {@inheritDoc}
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">contatoDao</span>.<span style="color: #006633;">getAgenda</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Mais uma vez aproveitamos da facilidade da injeção de dependência através de anotações para não nos preocuparmos em instanciar/recuperar o objeto <em>contatoDao</em>, o Spring se encarrega disso para nós.</p>
<p>Prontinho, com isso nós acabamos de incrementar a nossa pequena agenda com Spring e Hibernate! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>CONCLUSÃO</strong></p>
<p>Se testarmos a aplicação com essas alterações veremos que ela continua  funcionando exatamente da mesma maneira que estava funcionando antes porém agora com o Spring tomando conta da comunicação entre o Java e o  FLEX e o Hibernate persistindo os contatos no banco, quando formos adicionar novas funcionalidades temos que pensar apenas na funcionalidade, não precisamos ficar nos preocupando com os detalhes mais baixo nível (como a comunicação Java + FLEX). Tenho uma palavra para isso: produtividade! hehehe</p>
<p>Todo esse processo que realizamos é mais conhecido como refatoração: não mudamos nada do ponto de vista do usuário, apenas melhoramos a estrutura interna do aplicativo. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>O código fonte pode ser pego<a href="http://dl.dropbox.com/u/4918828/JavaSimples/Spring_Flex_Parte_2.rar"> aqui</a> (sem as bibliotecas).</p>
<p>[]s e até a próxima,</p>
<p>Saab.</p>
<p><strong>REFERÊNCIAS</strong></p>
<p>[1] <a title="An introduction to Spring BlazeDS Integration" href="http://www.adobe.com/devnet/flex/articles/spring_blazeds_integration.html" target="_blank">An introduction to Spring BlazeDS Integration</a></p>
<p>[2] <a title="Simple Flex Webapp" href="http://www.springbyexample.org/examples/simple-flex-webapp.html" target="_blank">Simple Flex Webapp</a></p>
<p>[3] <a title="Spring Flex" href="http://www.springsource.org/spring-flex" target="_blank">Página do projeto Spring BlazeDS Integration</a></p>
<p>[4] <a title="Using Spring BlazeDS Integration 1.0" href="http://blog.springsource.com/2009/06/10/using-spring-blazeds-integration-10/" target="_blank">Using Spring BlazeDS Integration 1.0</a></p>
<p>PS: Gostou? Não gostou? Ajudou? Não ajudou? Quebrou um galho? Perdeu 10 minutos da tua vida lendo? <strong>Comente! Divulgue! Fale mal! Compartilhe sua opinião com toda a comunidade! </strong><img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-2/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Java + FLEX Parte 1 -&gt; Integrando Java e FLEX</title>
		<link>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-1</link>
		<comments>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-1#comments</comments>
		<pubDate>Fri, 22 Apr 2011 23:39:00 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[FLEX]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[amf]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[blazeds]]></category>
		<category><![CDATA[builder]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[exemplo]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[messagebroker]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=410</guid>
		<description><![CDATA[Hoje iremos abordar uma integração (que eu particularmente acho) fantástica: Java e FLEX (cuja versão mais atual se chama Flash Builder 4). A primeira grande (super, ultra, &#8230;) vantagem que me vem na cabeça quando falo deste assunto é a facilidade para criar belas interfaces. Eu sou uma negação quando o assunto é criar interfaces, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/04/java-flash-icon1.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto;" title="java-flash-icon[1]" src="http://www.javasimples.com.br/wp-content/uploads/2011/04/java-flash-icon1.png" alt="" width="336" height="240" /></a></p>
<p>Hoje iremos abordar uma integração (que eu particularmente acho) fantástica: Java e FLEX (cuja versão mais atual se chama Flash Builder 4).</p>
<p>A primeira grande (super, ultra, &#8230;) vantagem que me vem na cabeça quando falo deste assunto é a<strong> facilidade para criar belas interfaces</strong>. Eu sou uma negação quando o assunto é criar interfaces, design me dá arrepios&#8230;</p>
<p>Outro ponto que é um grande vantagem é que toda a interface roda em cima do Flash, ou seja, basta ter o flash instalado no navegador e é certeza que o programa vai abrir exatamente do jeito que você o projetou! <strong>Não dá pau de navegador pra navegador!!!!</strong> Quem meche com CSS sabe do que eu estou falando, tua página está perfeita no Firefox e quando abre ela no IE dá até medo. Hahahaha quem nunca passou por isso que atire a primeira pedra.</p>
<p>Enfim, veremos como é possível ter uma interface fácil de desenvolver e ao mesmo tempo amigável para o usuário final com um backend poderosíssimo rodando o nosso bom e (não tão) velho Java e todos os frameworks que estamos acostumados a usar, como Spring e Hibernate.</p>
<p><span id="more-410"></span><br />
Esta série será dividida (a princípio) em 2 partes:</p>
<ul>
<li>
Parte 1 – Comunicação básica entre Java e FLEX</li>
<li>
Parte 2 – Integrando Spring e Hibernate na nossa aplicação</li>
</ul>
<p>Antes de começarmos propriamente dito com o tutorial deixe me falar como funciona essa integração: como o FLEX roda na máquina virtual do Flash que fica no browser (diferente do AIR que é desktop) a nossa aplicação Java também vai rodar em um servidor de aplicativos web (neste caso o Tomcat) para eles poderem se comunicar.</p>
<p>Ambos (FLEX e Java) rodando na web fazem com que o canal de comunicação fique na nossa cara: a própria WEB! Sendo assim, toda vez que o FLEX precisa se comunicar com o Java (quando o usuário manda salvar um objeto por exemplo) o FLEX envia uma mensagem (utilizando o protocolo AMF) para o Java através da WEB.</p>
<p>No servidor Java vai haver um servlet responsável por receber essas mensagens, decodificá-las, transformar os dados em objetos Java e encaminhar para a classe e método que tais objetos devem ser encaminhados e retornar o resultado para o FLEX.</p>
<p>Dita a teoria vamos a prática! hehehe</p>
<p>Vamos precisar ter algumas coisas instaladas:</p>
<p><a href="http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliossr1">Eclipse IDE</a><br />
<a href="https://www.adobe.com/cfusion/tdrc/index.cfm?product=flash_builder">Flash Builder 4 Eclipse Plugin</a> (Trial por 60 dias)<br />
<a href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS">BlazeDS 4 (Site da Adobe)</a> ou <a href="http://dl.dropbox.com/u/4918828/JavaSimples/blazeds-bin-4.0.1.17657.zip">local</a></p>
<p>Caso você já tenha o Eclipse instalado em sua máquina basta informar o caminho para ele durante a instalação que ele já instalará todos os plugins necessários. Caso não tenha o Eclipse basta baixar uma versão do Flash Builder que já vem com uma versão da IDE (porém não é a mais recente).</p>
<p>Depois que tudo estiver instalado vamos começar importando a estrutura base do projeto Java que vem junto com o arquivo do BlazeDS. No Eclipse selecione o menu <strong>Arquivo > Importar</strong> e selecione <strong>Arquivo WAR</strong> na categoria <strong>Web</strong>.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb.png" border="0" alt="image" width="235" height="240" /></a></p>
<p>Na próxima tela informe o caminho para o arquivo blazeds.war (que veio no arquivo do BlazeDS que você baixou) e informe o nome que o novo projeto vai ter. Iremos fazer uma simples (e bonita! hehe) agenda de contatos onde guardaremos os telefones e emails dos nossos amigos, então irei chamar o projeto de AgendaJ.</p>
<p>*OBS: Para o desenvolvimento Java + FLEX são criados 2 projetos: uma projeto Java e um projeto FLEX. Eu tenho o costume (e diria que é uma boa prática) de dar o mesmo nome aos dois projetos adicionando como sufixo J ou F caso o projeto seja Java ou FLEX, respectivamente.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image1.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb1.png" border="0" alt="image" width="237" height="240" /></a></p>
<p>Ok. Agora podemos dar uma espiada para ver como funciona toda a configuração da nossa aplicação Java. Vamos começar olhando para o deployment descriptor <strong>WebContent/WEB-INF/web.xml*</strong>:</p>
<p>*Apaguei os comentários que vieram junto com o arquivo pois não vamos utilizá-los.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;web-app<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>BlazeDS<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;description<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>BlazeDS Application<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/description<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- Http Flex Session attribute and binding listener support --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>flex.messaging.HttpFlexSession<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #808080; font-style: italic;">&lt;!-- MessageBroker Servlet --&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>MessageBrokerServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>MessageBrokerServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>flex.messaging.MessageBrokerServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>services.configuration.file<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/WEB-INF/flex/services-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/load-on-startup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>MessageBrokerServlet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/messagebroker/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/servlet-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;welcome-file-list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>index.html<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>index.htm<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/welcome-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/welcome-file-list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/web-app<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Foi definido um servlet chamado <strong>MessageBrokerServlet</strong> da classe <strong>flex.messaging.MessageBrokerServlet</strong> que recebe o parâmetro <strong>services.configuration.file</strong> indicando qual é o arquivo que contém as configurações dos serviços do FLEX. Conseguimos ver também que o <strong>MessageBrokerServlet</strong> recebe todas as requisições que chegam para a URL <strong>“…/messagebroker/*”</strong>, ou seja, sempre que o FLEX envia uma requisição para o Java já sabemos que é seguindo este padrão de URL (caso ainda não esteja claro já já vai ficar <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-smile.png" alt="Alegre" />).</p>
<p>Olhando o arquivo de configuração dos serviços (<strong>WebContent/WEB-INF/flex/services-config.xml</strong>)* podemos observar que:</p>
<p>*Retirei alguns comentários e fiz alguns pequenos ajustes nesse arquivo.</p>
<ul>
<li>ele inclui três outros arquivos de configuração através da tag <strong>&lt;service-include&gt;</strong> dentro da tag <strong>&lt;service&gt;</strong>;</li>
<li>diz qual classe vai ser responsável pela segurança (autenticação e autorização) em um servidor de aplicativos J2EE;</li>
<li>define quais canais estarão disponíveis para a comunicação através da tag<strong> &lt;channels&gt;</strong>. Cada canal definido dentro desta tag indica o mapeamento de um padrão de URL para uma classe em específico, por exemplo, a classe <strong>flex.messaging.endpoints.AMFEndpoint</strong> irá receber todas as requisições que forem para a URL <strong>“…/messagebroker/amf”</strong>;</li>
<li>configura o <strong>Logging</strong> das comunicações;</li>
<li>configura o redeploy automático de alguns arquivos que ele fica “observando” em intervalos de tempo definidos.</li>
</ul>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;services-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;service-include</span> <span style="color: #000066;">file-path</span>=<span style="color: #ff0000;">&quot;remoting-config.xml&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;service-include</span> <span style="color: #000066;">file-path</span>=<span style="color: #ff0000;">&quot;proxy-config.xml&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;service-include</span> <span style="color: #000066;">file-path</span>=<span style="color: #ff0000;">&quot;messaging-config.xml&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;login-command</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.security.TomcatLoginCommand&quot;</span> <span style="color: #000066;">server</span>=<span style="color: #ff0000;">&quot;Tomcat&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel-definition</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;my-amf&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;mx.messaging.channels.AMFChannel&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">url</span>=<span style="color: #ff0000;">&quot;http://{server.name}:{server.port}/{context.root}/messagebroker/amf&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.endpoints.AMFEndpoint&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channel-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel-definition</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;my-secure-amf&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;mx.messaging.channels.SecureAMFChannel&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">url</span>=<span style="color: #ff0000;">&quot;https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.endpoints.SecureAMFEndpoint&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add-no-cache-headers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/add-no-cache-headers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channel-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel-definition</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;my-polling-amf&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;mx.messaging.channels.AMFChannel&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">url</span>=<span style="color: #ff0000;">&quot;http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.endpoints.AMFEndpoint&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;polling-enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/polling-enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;polling-interval-seconds<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>4<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/polling-interval-seconds<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channel-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;logging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;target</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.log.ConsoleTarget&quot;</span> <span style="color: #000066;">level</span>=<span style="color: #ff0000;">&quot;Error&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prefix<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>[BlazeDS] <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prefix<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeDate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeDate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeTime<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeTime<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includeCategory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includeCategory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Endpoint.*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Service.*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Configuration<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/target<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/logging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;redeploy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/enabled<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>20<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/flex/services-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/flex/proxy-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/flex/remoting-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/flex/messaging-config.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/watch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;touch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>{context.root}/WEB-INF/web.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/touch-file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/redeploy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/services-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>OBS: perceba que todos os canais tem o padrão de URL parecido (<strong>“…/messagebroker/…”</strong>). Por isso que o <strong>MessageBrokerServlet</strong> recebe todas as requisições para a URL <strong>“…/messagebroker/*”</strong>, ele verifica para qual canal ela vai e encaminha para a classe correta. <img class="wlEmoticon wlEmoticon-winkingsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-winkingsmile.png" alt="Smiley piscando" /></p>
<p>Os outros arquivos de configuração não contém nada que precise chamar a atenção agora. Então já dá pra dizer que sabemos como o Java recebe e trata as requisições do FLEX! <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p>Vamos preparar o backend da nossa aplicação então: vamos criar a classe que vai representar um contato da nossa agenda e um serviço para executar as regras de negócio da nossa aplicação:</p>
<p>Contato.java</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Serializable</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>1549466344815889020L<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> telefone<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> email<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getNome<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setNome<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nome</span> <span style="color: #339933;">=</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getTelefone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> telefone<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setTelefone<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> telefone<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">telefone</span> <span style="color: #339933;">=</span> telefone<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getEmail<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> email<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setEmail<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> email<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">email</span> <span style="color: #339933;">=</span> email<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		StringBuilder sb <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getTelefone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;,&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getEmail</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A classe que representa um contato possui apenas o nome, telefone e email do contato. Suficiente para nossa pequena agenda. <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-smile.png" alt="Alegre" /></p>
<p>OBS: essa classe implementa a interface <strong>java.io.Serializable</strong> pois ela vai trafegar na Web (do Java para o FLEX e vice versa). É aconselhavel que todo objeto que for ser transmitido através de um canal (socket, web, etc) implemente esta interface e tenha o <strong>serialVersionUID</strong> (que o Eclipse gerou pra mim hehe) que indica um número único para identificar aquela classe.</p>
<p>Vamos ver agora o serviço que irá tratar a inserção de novos contatos na nossa agenda:</p>
<p>ContatoService.java</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContatoService <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> agenda <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span>Contato contato<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		ContatoService.<span style="color: #006633;">agenda</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Contato adicionado: &quot;</span> <span style="color: #339933;">+</span> contato<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>contato<span style="color: #339933;">&gt;</span> getAgenda<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> ContatoService.<span style="color: #006633;">agenda</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como ainda não vamos utilizar o banco de dados e o Hibernate nesta parte do tutorial vamos simular um &#8220;banco de dados&#8221; (está entre aspas duplas tá.. hehehe) com uma lista estática.</p>
<p>O método <strong>salvar(Contato)</strong> simplesmente adiciona um novo contato na agenda e o método <strong>getAgenda()</strong> retorna a nossa agenda com todos os contatos.</p>
<p>Esses métodos vão ser utilizados para o FLEX pedir para o Java salvar um novo contato na agenda e para ele recuperar a agenda com os contatos atualizados.</p>
<p>Para finalizar o desenvolvimento do nosso backend precisamos apenas expor nossa classe de serviço para que as classes que recebem a requisição do FLEX (pacote <strong>flex.messaging.endpoint</strong>) consigam localizá-la em tempo de execução.</p>
<p>Para isso adicionaremos uma nova tag<strong> &lt;destination&gt;</strong> no arquivo <strong>WebContent/WEB-INF/flex/remoting-config.xml</strong> informando um ID para este novo destino e qual classe é responsável por tratar as requisições destinadas a ele. Desta maneira nós informaremos este mesmo ID no FLEX quando precisarmos chamar algum método desta classe.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;service</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;remoting-service&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.services.RemotingService&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;adapters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;adapter-definition</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;java-object&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;flex.messaging.services.remoting.adapters.JavaAdapter&quot;</span> <span style="color: #000066;">default</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/adapters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;default-channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;channel</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;my-amf&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/default-channels<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;destination</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contatoService&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;source<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.blog.javasimples.agenda.service.ContatoService<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/source<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/destination<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/service<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Agora já podemos deixar o Java um pouco de lado e ir pra parte nova: o FLEX! <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p>Vamos criar um novo projeto no Eclipse: <strong>Arquivo &gt; Novo &gt; Projeto</strong>. Na categoria <strong>Flash Builder</strong> vamos escolher um <strong>Flex Project</strong>. Na primeira tela configuramos o nome do projeto (vou colocar AgendaF como já comentei lá em cima), dizemos que ele vai rodar na Web e vai se comunicar com um servidor J2EE utilizando o BlazeDS.</p>
<p>OBS: tenha certeza de que o checkbox “Create combined Java/Flex project using WTP” está DESMARCADO.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image2.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb2.png" border="0" alt="image" width="173" height="240" /></a></p>
<p>Na próxima tela informamos algumas configurações do servidor J2EE (no meu caso o Tomcat):</p>
<ul>
<li>Root folder –&gt; O caminho pra raiz da aplicação Java no disco;</li>
<li>Root URL –&gt; O caminho para a raiz da aplicação Java através do servidor;</li>
<li>Context Root –&gt; O contexto da aplicação no servidor;</li>
<li>Output Folder (o Eclipse sugere) –&gt; Caminho para a pasta onde o projeto FLEX será compilado e ficará “guardado”. Fica dentro da raiz da aplicação Java pra ser executada junto com o servidor.</li>
</ul>
<p>&nbsp;</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image3.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb3.png" border="0" alt="image" width="240" height="160" /></a></p>
<p>Na próxima tela temos que adicionar uma pasta que será a raíz dos códigos fonte. Na aba<strong> Source Path</strong> apenas clique em<strong> Add Folder…</strong> e crie uma nova pasta com o nome <strong>src</strong>.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image4.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb4.png" border="0" alt="image" width="240" height="201" /></a></p>
<p>Após criado o projeto temos mais um ajuste a fazer: caso o Flash Builder 4 que você tenha baixado veio na língua inglesa e seu sistema operacional esteja em português o Eclipse vai criar uma configuração em português (porque ele “reflete” o locale do SO) e o Flash Builder não vai se dar muito bem com ele não… hehehe</p>
<p>Para corrigir esse parâmetro vamos nas propriedades do projeto (<strong>botão direito no projeto &gt; Propriedades</strong>) e na categoria <strong>Flex Compiler </strong>existe o campo de texto Additional compiler arguments onde está escrito “<strong>-services …\services-config.xml –locale pt_BR</strong>”. Vamos apenas trocar o parâmetro “<strong>-locale pt_BR</strong>” por “<strong>-locale en_US</strong>”.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image5.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb5.png" border="0" alt="image" width="240" height="162" /></a></p>
<p>Legal, vamos começar a programar mesmo. Mude a perspectiva do Eclipe para Flash (caso ainda não tenha o feito). Vamos entrar em outro mundo agora, vamos deixar o Java um pouco de lado e programar em <strong>ActionScript 3</strong> (aka <strong>AS3</strong>), linguagem utilizada na plataforma FLEX (e outras da Adobe).</p>
<p>OBS: eu não vou entrar em detalhes da linguagem propriamente dita, uma vez que o nome do blog não é AS3 Simples.. kkkkkkkk Mas não tem diferenças muito grandes não, uma pessoa que está acostumada com Java consegue pegar o AS3 rapidinho. <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p>Vamos começar criando a classe que representa um contato da agenda. Vamos criar um pacote com o mesmo nome do pacote no Java (outra boa prática) e criar uma ActionScript Class com o mesmo nome (Contato.as):</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image6.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb6.png" border="0" alt="image" width="240" height="157" /></a></p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package br.<span style="color: #006600;">blog</span>.<span style="color: #006600;">javasimples</span>.<span style="color: #006600;">agenda</span>.<span style="color: #006600;">model</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span>
	<span style="color: #66cc66;">&#91;</span>RemoteClass<span style="color: #66cc66;">&#40;</span>alias=<span style="color: #ff0000;">&quot;br.blog.javasimples.agenda.model.Contato&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Contato
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> nome:<span style="color: #0066CC;">String</span>;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> telefone:<span style="color: #0066CC;">String</span>;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">var</span> email:<span style="color: #0066CC;">String</span>;
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>A classe que representa o contato do lado do FLEX deve possuir os atributos com os mesmos nomes do nome de atributo extraído dos getters da classe Java. Estranho né&#8230; heheheh Vamos ver com um pequeno exemplo:</p>
<p>Na classe Contato.java eu tenho os getters <em>getNome()</em>, <em>getTelefone()</em> e <em>getEmail()</em>. Quando o BlazeDS vai enviar os dados do Java para o FLEX ele vai fazer um algorítmo que siga uma lógica parecida com essa (não olhei no código fonte pra saber se é assim mesmo, porém o resultado final é algo assim):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> getterName <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;getEmail&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> attributeName <span style="color: #339933;">=</span> getterName.<span style="color: #006633;">replaceFirst</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;get&quot;</span>,<span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// attributeName == &quot;Email&quot;</span>
attributeName <span style="color: #339933;">=</span> attributeName.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toUpperCase</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> attributeName.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// // attributeName == &quot;email&quot;</span></pre></div></div>

<p>Ou seja, com os getters <em>getNome()</em>, <em>getTelefone()</em> e <em>getEmail()</em> o BlazeDS vai enviar os valores para a classe Contato.as esperando que existam os atributos <em>nome</em>, <em>telefone </em>e <em>email</em>.</p>
<p>O BlazeDS segue esse mesmo padrão para enviar os dados do FLEX para o Java, ou seja, os setters devem seguir esse mesmo padrão de nomenclatura.</p>
<p>Continuando com a nossa classe, algo novo para quem nunca usou AS3 são as anotações: [Bindable] e [RemoteClass(alias)].</p>
<p>Se essas anotações fossem em Java seriam: @Bindable e @RemoteClass(alias=”…”). Só a primeira vista que confunde um pouco, mas é a mesma coisa.</p>
<p>Segue o significado de tais anotações:</p>
<ul>
<li>[Bindable] – é algo como a implementação do design pattern Observer. Todo lugar que estiver referenciando alguma propriedade dessa classe será imediatamente avisado assim que alguma delas sofrer alguma mudança;</li>
<li>[RemoteClasse(alias)] – indica para o BlazeDS qual a classe correspondente a essa na aplicação Java.</li>
</ul>
<p>Tão simples quanto fazer um POJO no Java não?! hehehe</p>
<p>Agora vem a parte que me fascina no FLEX: layout! <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p>Vamos abrir o arquivo AgendaF.mxml que o Eclipse gerou para nós. Ao mudar para a aba design nós podemos criar a nossa tela com um simples clicar e arrastar de componentes. Arrastei alguns componentes e mudei os labels e em menos de 10 minutos eu fiz o design da nossa aplicação de exemplo:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image8.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb8.png" border="0" alt="image" width="240" height="142" /></a></p>
<p>O código do arquivo AgendaF.mxml ficou assim:</p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Application</span> xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span></span>
<span style="color: #000000;">               xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span></span>
<span style="color: #000000;">               xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Form</span> width=<span style="color: #ff0000;">&quot;500&quot;</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Nome&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> id=<span style="color: #ff0000;">&quot;txtNome&quot;</span> width=<span style="color: #ff0000;">&quot;220&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Telefone&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;100&quot;</span> id=<span style="color: #ff0000;">&quot;txtTelefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Email&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;220&quot;</span> id=<span style="color: #ff0000;">&quot;txtEmail&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Button</span> label=<span style="color: #ff0000;">&quot;Salvar&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Nome&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Telefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Email&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/s:Application</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>OBS: perceba que os <strong>TextInput</strong>s tem <strong>id</strong>s definidos. Isso para que possamos recuperar os seus valores via programação logo mais.</p>
<p>Para vermos como vai ficar esse layout no browser basta rodar o projeto AgendaJ primeiro e depois o AgendaF.</p>
<ul>
<li>AgendaJ – botão direito no projeto &gt; Run As &gt; Run on Server</li>
<li>AgendaF – botão direito no projeto &gt; Run As &gt; Web Application</li>
</ul>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image9.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb9.png" border="0" alt="image" width="240" height="154" /></a></p>
<p>Vamos fazer isso funcionar agora!</p>
<p>Vamos começar com a funcionalidade de salvar um contato: toda vez que o botão Salvar for pressionado iremos criar um objeto Contato e enviar para o Java, mais especificamente para o método <strong>salvar(Contato) </strong>da classe <strong>ContatoService</strong>.</p>
<p>Para isso vamos precisar de uma área para programar em ActionScript dentro do arquivo AgendaF.mxml, que como o nome indica (e conseguimos ver através da aba Source) é um XML. Tal área fica disponível através da tag &lt;fx:Script&gt;.</p>
<p>Segue o código que salva um novo contato:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #66cc66;">&lt;</span>s:Application xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span>
               xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span>
               xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span><span style="color: #66cc66;">&gt;</span>
&nbsp;
<span style="color: #66cc66;">&lt;</span>fx:Script<span style="color: #66cc66;">&gt;</span>
        <span style="color: #66cc66;">&lt;!</span><span style="color: #66cc66;">&#91;</span>CDATA<span style="color: #66cc66;">&#91;</span>
            <span style="color: #0066CC;">import</span> br.<span style="color: #006600;">blog</span>.<span style="color: #006600;">javasimples</span>.<span style="color: #006600;">agenda</span>.<span style="color: #006600;">model</span>.<span style="color: #006600;">Contato</span>;
&nbsp;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">controls</span>.<span style="color: #006600;">Alert</span>;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">AsyncToken</span>;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">Responder</span>;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">events</span>.<span style="color: #006600;">FaultEvent</span>;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">events</span>.<span style="color: #006600;">ResultEvent</span>;
            <span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">remoting</span>.<span style="color: #006600;">RemoteObject</span>;
&nbsp;
            <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> remoteObject:RemoteObject=<span style="color: #000000; font-weight: bold;">new</span> RemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;contatoService&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
            <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> salvaContato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
            <span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">var</span> contato:Contato=<span style="color: #000000; font-weight: bold;">new</span> Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
                contato.<span style="color: #006600;">nome</span>=txtNome.<span style="color: #0066CC;">text</span>;
                contato.<span style="color: #006600;">telefone</span>=txtTelefone.<span style="color: #0066CC;">text</span>;
                contato.<span style="color: #006600;">email</span>=txtEmail.<span style="color: #0066CC;">text</span>;
&nbsp;
                <span style="color: #808080; font-style: italic;">// Insere esse contato na lista do Java</span>
                <span style="color: #000000; font-weight: bold;">var</span> token:AsyncToken=remoteObject.<span style="color: #006600;">salvar</span><span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;
                token.<span style="color: #006600;">addResponder</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> mx.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">Responder</span><span style="color: #66cc66;">&#40;</span>salvarSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
&nbsp;
            <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> salvarSucesso<span style="color: #66cc66;">&#40;</span>result:ResultEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
            <span style="color: #66cc66;">&#123;</span>
                Alert.<span style="color: #0066CC;">show</span><span style="color: #66cc66;">&#40;</span>“Contato salvo com sucesso<span style="color: #66cc66;">!</span>”<span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
&nbsp;
            <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> erro<span style="color: #66cc66;">&#40;</span>event:FaultEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
            <span style="color: #66cc66;">&#123;</span>
                Alert.<span style="color: #0066CC;">show</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Ocorreu o seguinte erro: &quot;</span> + event.<span style="color: #006600;">fault</span>.<span style="color: #006600;">faultString</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&gt;</span>
    <span style="color: #66cc66;">&lt;/</span>fx:Script<span style="color: #66cc66;">&gt;</span>
&nbsp;
   <span style="color: #66cc66;">&lt;!</span>-- ..... --<span style="color: #66cc66;">&gt;</span>
&nbsp;
<span style="color: #66cc66;">&lt;/</span>s:Application<span style="color: #66cc66;">&gt;</span></pre></div></div>

<p>Vamos começar de cima para baixo:</p>
<p>Primeiro temos a declaração e instanciação de um objeto da classe <strong>RemoteObject</strong>. Essa classe é a responsável por fazer a comunicação com outra classe do lado do Java. Para criarmos esse vínculo basta passarmos o <strong>ID</strong> que definimos para a classe Java (no arquivo <strong>WebContent/WEB-INF/flex/remoting-config.xml</strong>) no construtor do <strong>RemoteObject</strong>.</p>
<p>No nosso caso a classe <strong>ContatoService.java </strong>está vinculada dentro da tag <strong>&lt;destination id=”contatoService”&gt; </strong>no arquivo <strong>remoting-config.xml </strong>então utilizamos este mesmo <strong>ID </strong>no construtor do nosso obejto.</p>
<p>Vamos olhar agora para o método <strong>salvaContato():</strong> é criado um novo objeto <strong>Contato </strong>e seus dados são preenchidos com os valores dos <strong>TextInput</strong>s. Logo depois utilizamos o <strong>RemoteObject</strong> para invocar o método <strong>salvar(Contato)</strong> da classe a que ele está vinculado (<strong>ContatoService.java</strong>).</p>
<p>Para invocar os métodos remotos nós temos que <strong>imaginar </strong>que o <strong>RemoteObject </strong>é a classe que queremos utilizar (neste caso <strong>ContatoService</strong>). Exemplo: na classe <strong>ContatoService </strong>nós temos o método <strong>salvar(Contato)</strong>. Para executar esse método através do <strong>RemoteObject </strong>basta executar um método com o<strong> <span style="text-decoration: underline;">mesmo nome e com os mesmos parâmetros</span> </strong>(super usual né <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-smile.png" alt="Alegre" />).</p>
<p>Continuando, todas as chamadas a métodos remotos são assíncronas, ou seja, temos que esperar voltar uma resposta do Java para receber o retorno do método ou uma possível falha (caso seja jogada alguma Exception).</p>
<p>Para lidarmos com isso, todo método remoto executado através do <strong>RemoteObject </strong>retorna um <strong>AsyncToken</strong>. Através deste <strong>AsyncToken </strong>nós podemos ser notificados sempre que o método remoto retorna algo (o retorno do método ou uma exception).</p>
<p>Para isso nós adicionamos um <strong>Responder </strong>no <strong>AsyncToken</strong>. O construtor do <strong>Responder </strong>requer que passemos duas funções de parâmetro: a primeira será chamada quando o método remoto for concluído com sucesso e a segunda será chamada quando o método remoto jogar um erro.</p>
<p>A função que vai ser chamada quando o método remoto for concluído vai receber um <strong>ResultEvent</strong> como parâmetro (na grande maioria das vezes, porém não é regra) e caso o método remoto retornasse algum objeto nós conseguimos acessar esse retorno atavés do atributo <strong>result</strong> do objeto <strong>ResultEvent</strong>.</p>
<p>Já no caso da função que vai ser chamada quando o método remoto jogar um erro, ela recebe um <strong>FaultEvent </strong>(na maioria dos casos, porém também não é regra). E para acessar detalhes sobre o erro que foi jogado utilizamos o atributo <strong>fault </strong>do objeto <strong>FaultEvent</strong>.</p>
<p>Voltando para o nosso código, quando o método ContatoService.salvar(Contato) terminar de salvar o contato na lista nós exibiremos uma mensagem informando o usuário de que o novo contato foi salvo.</p>
<p>Ao executarmos o projeto e inserir um novo contato acontece o seguinte:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image10.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb10.png" border="0" alt="image" width="240" height="154" /></a></p>
<p>E se observarmos o console do Eclipse também vamos ver:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image11.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb11.png" border="0" alt="image" width="240" height="53" /></a></p>
<p>Porém a grid ainda continua vazia… Vamos configurá-la então:</p>
<p>Todos os registros que aparecem em uma DataGrid devem estar em um  array, uma lista ou algo parecido (por hora um Array está ótimo! hehehe). O Array que contém os dados que serão mostrados na DataGrid deve alimentar o atributo dataProvider dela. Vamos então criar um Array e alimentar a nossa grid:</p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Application</span> xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span></span>
<span style="color: #000000;">               xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span></span>
<span style="color: #000000;">               xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;">&lt;!<span style="color: #66cc66;">&#91;</span>CDATA<span style="color: #66cc66;">&#91;</span></span>
<span style="color: #000000;">            import br.blog.javasimples.agenda.model.Contato;</span>
&nbsp;
<span style="color: #000000;">            import mx.collections.ArrayCollection;</span>
<span style="color: #000000;">            import mx.controls.Alert;</span>
<span style="color: #000000;">            import mx.rpc.AsyncToken;</span>
<span style="color: #000000;">            import mx.rpc.Responder;</span>
<span style="color: #000000;">            import mx.rpc.events.FaultEvent;</span>
<span style="color: #000000;">            import mx.rpc.events.ResultEvent;</span>
<span style="color: #000000;">            import mx.rpc.remoting.RemoteObject;</span>
&nbsp;
<span style="color: #000000;">            private var remoteObject:RemoteObject=new RemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;contatoService&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">            <span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span></span>
<span style="color: #000000;">            private var agenda:ArrayCollection=new ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">            private function salvaContato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                var contato:Contato=new Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">                contato.nome=txtNome.text;</span>
<span style="color: #000000;">                contato.telefone=txtTelefone.text;</span>
<span style="color: #000000;">                contato.email=txtEmail.text;</span>
&nbsp;
<span style="color: #000000;">                // Insere esse contato na lista do Java</span>
<span style="color: #000000;">                var token:AsyncToken=remoteObject.salvar<span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">                token.addResponder<span style="color: #66cc66;">&#40;</span>new mx.rpc.Responder<span style="color: #66cc66;">&#40;</span>salvarSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">            private function salvarSucesso<span style="color: #66cc66;">&#40;</span>result:ResultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Contato salvo com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">            private function erro<span style="color: #66cc66;">&#40;</span>event:FaultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Ocorreu o seguinte erro: &quot;</span> + event.fault.faultString<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">        <span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span><span style="color: #7400FF;">&gt;</span></span>
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Form</span> width=<span style="color: #ff0000;">&quot;500&quot;</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Nome&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> id=<span style="color: #ff0000;">&quot;txtNome&quot;</span> width=<span style="color: #ff0000;">&quot;220&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Telefone&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;100&quot;</span> id=<span style="color: #ff0000;">&quot;txtTelefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Email&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;220&quot;</span> id=<span style="color: #ff0000;">&quot;txtEmail&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Button</span> label=<span style="color: #ff0000;">&quot;Salvar&quot;</span> click=<span style="color: #ff0000;">&quot;this.salvaContato()&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> dataProvider=<span style="color: #ff0000;">&quot;{this.agenda}&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Nome&quot;</span> dataField=<span style="color: #ff0000;">&quot;nome&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Telefone&quot;</span> dataField=<span style="color: #ff0000;">&quot;telefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Email&quot;</span> dataField=<span style="color: #ff0000;">&quot;email&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/s:Application</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>Foi criado um <strong>ArrayCollection </strong>chamado agenda e talvariável foi passada para o atributo <strong>dataProvider </strong>da <strong>DataGrid</strong>, sendo assim todos os elementos que estiverem dentro do <strong>ArrayCollection </strong>irão aparecer na grid também.</p>
<p>Indicamos também nas colunas qual atributo dos objetos que estão dentro do <strong>dataProvider </strong>deve ser exibido através do atributo <strong>dataField</strong>.</p>
<p>Tudo o que precisamos fazer agora é adicionar os nossos contatos nesse ArrayCollection agora. Vamos fazer o seguinte, toda vez que um novo contato for salvo nós iremos chamar o método getAgenda() da classe ContatoService e armazenar o retorno do método na variável agenda que acabamos de criar, assim manteremos a lista sempre atualizada e consequentemente a grid com todos os nossos contatos.</p>

<div class="wp_syntax"><div class="code"><pre class="mxml" style="font-family:monospace;"><span style="color: #000000;">&lt;?xml version=<span style="color: #ff0000;">&quot;1.0&quot;</span> encoding=<span style="color: #ff0000;">&quot;utf-8&quot;</span>?<span style="color: #7400FF;">&gt;</span></span>
<span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Application</span> xmlns:fx=<span style="color: #ff0000;">&quot;http://ns.adobe.com/mxml/2009&quot;</span></span>
<span style="color: #000000;">               xmlns:s=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/spark&quot;</span></span>
<span style="color: #000000;">               xmlns:mx=<span style="color: #ff0000;">&quot;library://ns.adobe.com/flex/mx&quot;</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;">&lt;!<span style="color: #66cc66;">&#91;</span>CDATA<span style="color: #66cc66;">&#91;</span></span>
<span style="color: #000000;">            import br.blog.javasimples.agenda.model.Contato;</span>
&nbsp;
<span style="color: #000000;">            import mx.collections.ArrayCollection;</span>
<span style="color: #000000;">            import mx.controls.Alert;</span>
<span style="color: #000000;">            import mx.rpc.AsyncToken;</span>
<span style="color: #000000;">            import mx.rpc.Responder;</span>
<span style="color: #000000;">            import mx.rpc.events.FaultEvent;</span>
<span style="color: #000000;">            import mx.rpc.events.ResultEvent;</span>
<span style="color: #000000;">            import mx.rpc.remoting.RemoteObject;</span>
&nbsp;
<span style="color: #000000;">            private var remoteObject:RemoteObject=new RemoteObject<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;contatoService&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">            <span style="color: #66cc66;">&#91;</span>Bindable<span style="color: #66cc66;">&#93;</span></span>
<span style="color: #000000;">            private var agenda:ArrayCollection=new ArrayCollection<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">            private function salvaContato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                var contato:Contato=new Contato<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">                contato.nome=txtNome.text;</span>
<span style="color: #000000;">                contato.telefone=txtTelefone.text;</span>
<span style="color: #000000;">                contato.email=txtEmail.text;</span>
&nbsp;
<span style="color: #000000;">                // Insere esse contato na lista do Java</span>
<span style="color: #000000;">                var token:AsyncToken=remoteObject.salvar<span style="color: #66cc66;">&#40;</span>contato<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">                token.addResponder<span style="color: #66cc66;">&#40;</span>new mx.rpc.Responder<span style="color: #66cc66;">&#40;</span>salvarSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">            private function salvarSucesso<span style="color: #66cc66;">&#40;</span>result:ResultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Contato salvo com sucesso!&quot;</span><span style="color: #66cc66;">&#41;</span>;</span>
&nbsp;
<span style="color: #000000;">                // Recupera a lista completa</span>
<span style="color: #000000;">                var token:AsyncToken=remoteObject.getAgenda<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">                token.addResponder<span style="color: #66cc66;">&#40;</span>new mx.rpc.Responder<span style="color: #66cc66;">&#40;</span>getAgendaSucesso, erro<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">            private function getAgendaSucesso<span style="color: #66cc66;">&#40;</span>event:ResultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                this.agenda=event.result as ArrayCollection;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">            private function erro<span style="color: #66cc66;">&#40;</span>event:FaultEvent<span style="color: #66cc66;">&#41;</span>:void</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #000000;">                Alert.show<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Ocorreu o seguinte erro: &quot;</span> + event.fault.faultString<span style="color: #66cc66;">&#41;</span>;</span>
<span style="color: #000000;">            <span style="color: #66cc66;">&#125;</span></span>
&nbsp;
<span style="color: #000000;">        <span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span><span style="color: #7400FF;">&gt;</span></span>
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;/fx:Script</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Form</span> width=<span style="color: #ff0000;">&quot;500&quot;</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Nome&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> id=<span style="color: #ff0000;">&quot;txtNome&quot;</span> width=<span style="color: #ff0000;">&quot;220&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Telefone&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;100&quot;</span> id=<span style="color: #ff0000;">&quot;txtTelefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:FormItem</span> label=<span style="color: #ff0000;">&quot;Email&quot;</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> direction=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:TextInput</span> width=<span style="color: #ff0000;">&quot;220&quot;</span> id=<span style="color: #ff0000;">&quot;txtEmail&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:Spacer</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> height=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;s:Button</span> label=<span style="color: #ff0000;">&quot;Salvar&quot;</span> click=<span style="color: #ff0000;">&quot;this.salvaContato()&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:FormItem</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:HBox</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGrid</span> width=<span style="color: #ff0000;">&quot;100%&quot;</span> dataProvider=<span style="color: #ff0000;">&quot;{this.agenda}&quot;</span><span style="color: #7400FF;">&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Nome&quot;</span> dataField=<span style="color: #ff0000;">&quot;nome&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Telefone&quot;</span> dataField=<span style="color: #ff0000;">&quot;telefone&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                    <span style="color: #000000;"><span style="color: #7400FF;">&lt;mx:DataGridColumn</span> headerText=<span style="color: #ff0000;">&quot;Email&quot;</span> dataField=<span style="color: #ff0000;">&quot;email&quot;</span><span style="color: #7400FF;">/&gt;</span></span>
                <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:columns</span><span style="color: #7400FF;">&gt;</span></span>
            <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:DataGrid</span><span style="color: #7400FF;">&gt;</span></span>
        <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:HBox</span><span style="color: #7400FF;">&gt;</span></span>
    <span style="color: #000000;"><span style="color: #7400FF;">&lt;/mx:Form</span><span style="color: #7400FF;">&gt;</span></span>
&nbsp;
<span style="color: #000000;"><span style="color: #7400FF;">&lt;/s:Application</span><span style="color: #7400FF;">&gt;</span></span></pre></div></div>

<p>Prontinho! Ao rodar a aplicação de novo e adicionar mais contatos conseguimos ver que agora tudo está funcionando perfeitamente! <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/05/image12.png"><img style="background-image: none; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border: 0px;" title="image" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/image_thumb12.png" border="0" alt="image" width="240" height="154" /></a></p>
<p>Bom, confesso que este post ficou um pouco maior do que eu imaginei inicialmente… hehehe</p>
<p>Mas o importante é que deu pra passar a idéia sobre como funciona a integração do Java e do FLEX e como pessoas cujo dom na área de design não é muito elevado (como eu) podem fazer aplicações bonitas e amigáveis para o usuário final! <img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
<p>O código fonte desses projeto está disponível <a href="http://dl.dropbox.com/u/4918828/JavaSimples/FLEX_Java_Agenda.rar">aqui</a>.</p>
<p>Veja a <a href="http://www.javasimples.com.br/spring-2/java-spring-hibernate-flex-flash-builder-4-%E2%80%93-parte-2/">parte 2</a> também..! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>[]s e até a próxima,</p>
<p>Saab.</p>
<p>PS: Gostou? Não gostou? Ajudou? Não ajudou? Quebrou um galho? Perdeu 10 minutos da tua vida lendo? <strong>Comente! Divulgue! Fale mal! Compartilhe sua opinião com toda a comunidade! </strong><img class="wlEmoticon wlEmoticon-openmouthedsmile" style="border-style: none;" src="http://www.javasimples.com.br/wp-content/uploads/2011/05/wlEmoticon-openmouthedsmile.png" alt="Smiley de boca aberta" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/flex/java-spring-hibernate-flex-flash-builder-4-parte-1/feed</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Java Magazine 90 &#8211; Hibernate Annotations</title>
		<link>http://www.javasimples.com.br/hibernate-2/java-magazine-90-hibernate-annotations</link>
		<comments>http://www.javasimples.com.br/hibernate-2/java-magazine-90-hibernate-annotations#comments</comments>
		<pubDate>Thu, 21 Apr 2011 15:09:43 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Outras]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[banco]]></category>
		<category><![CDATA[dados]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java magazine]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[netbeans]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=369</guid>
		<description><![CDATA[É com grande prazer que venho informar que escrevi um artigo sobre Hibernate Annotations para a revista Java Magazine e o artigo foi publicado na edição número 90. Segue um pequeno resumo do artigo: Hibernate Annotations &#8211; Mapeamento Objeto Relacional através de Anotações Desde que surgiu o Hibernate para ser uma ponte entre a orientação [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/04/java-magazine1.jpg"><img class="aligncenter size-full wp-image-370" title="java-magazine[1]" src="http://www.javasimples.com.br/wp-content/uploads/2011/04/java-magazine1.jpg" alt="" width="267" height="125" /></a></p>
<p>É com grande prazer que venho informar que escrevi um artigo sobre Hibernate Annotations para a revista Java Magazine e o artigo foi publicado na edição número 90.</p>
<p>Segue um pequeno resumo do artigo:</p>
<blockquote><p><strong>Hibernate Annotations &#8211; Mapeamento Objeto Relacional através de Anotações</strong></p>
<p>Desde que surgiu o Hibernate para ser uma ponte entre a orientação a objetos e a persistência de dados em bancos de dados relacionais, tudo o que o desenvolvedor precisa fazer é descrever suas classes com alguns metadados para poder se focar no desenvolvimento da aplicação (regras de negócio). Assim, sem se preocupar muito com a persistência de seus objetos em bancos de dados o desenvolvedor consegue aumentar sua produtividade.</p>
<p>Durante um bom tempo os metadados foram descritos através de XML (e são até hoje). Para cada classe que seria persistida no banco de dados era criado um novo XML explicando como o Hibernate deveria realizar o mapeamento entre atributos da classe e colunas da tabela.</p>
<p>Atualmente este não é mais o único modo de descrever os metadados, existe também o Hibernate Annotations, projeto que provê a descrição dos metadados através de anotações. Deste modo, ao invés de um arquivo XML para cada classe, os metadados podem ser anotados na própria classe e em seus atributos, facilitando ainda mais o processo de mapeamento.</p>
<p>Nesse artigo serão apresentados os conceitos necessários para entender como utilizar o framework Hibernate para persistir as classes Java em bancos de dados relacionais apenas com a descrição de metadados providos por anotações, utilizando, para isso, a IDE NetBeans 6.9.1 e o banco de dados MySQL.</p></blockquote>
<p>Caso o assunto seja de seu interesse pode dar um pulo no <a title="Java Magazine 90" href="http://www.devmedia.com.br/post-20429-Revista-Java-Magazine-90.html" target="_blank">site da revista</a> ou então dar uma conferida nas bancas..</p>
<p>[]s,<br />
Saab.</p>
<p>PS: Isso não foi marketing! Estou feliz pois meu primeiro artigo para a revista foi publicado. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/hibernate-2/java-magazine-90-hibernate-annotations/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring Framework Parte 5 -&gt; Spring Web MVC</title>
		<link>http://www.javasimples.com.br/spring-2/spring-framework-parte-5-spring-web-mvc</link>
		<comments>http://www.javasimples.com.br/spring-2/spring-framework-parte-5-spring-web-mvc#comments</comments>
		<pubDate>Tue, 01 Feb 2011 00:28:19 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[padrao]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[projeto]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=293</guid>
		<description><![CDATA[Antes de entrar no assunto deixe-me dar aquele aviso de praxe: caso você não ainda não conheça o básico do Spring Framework dê uma olhadinha nos posts anteriores dessa série: Spring Framework Parte 1 -&#62; Dependency Injection Spring Framework Parte 2 -&#62; Aspect Oriented Programming Spring Framework Parte 3 -&#62; Java Database Connectivity (JDBC) Spring [...]]]></description>
			<content:encoded><![CDATA[<p><!--:pt-->
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/01/mvc1.jpg"><img class="aligncenter size-full wp-image-295" title="mvc" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/mvc1.jpg" alt="" width="430" height="306" /></a></p>
<p>Antes de entrar no assunto deixe-me dar aquele aviso de praxe: caso você não ainda não conheça o básico do Spring Framework dê uma olhadinha nos posts anteriores dessa série:</p>
<ul>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-1-dependency-injection/" target="_blank">Spring Framework Parte 1 -&gt; Dependency Injection</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-2-aspect-oriented-programming/" target="_blank">Spring Framework Parte 2 -&gt; Aspect Oriented Programming</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-3-java-database-connectivity-jdbc/" target="_blank">Spring Framework Parte 3 -&gt; Java Database Connectivity (JDBC)</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-4-integracao-com-o-hibernate/" target="_blank">Spring Framework Parte 4 -&gt; Integração com o Hibernate</a></li>
<li><a href="http://www.javasimples.com.br/mundo-java/spring-security-3-deixando-sua-aplicacao-web-segura/" target="_blank">Spring Security 3 -&gt; Deixando sua aplicação Web segura!</a></li>
</ul>
<p><br/><br />
Beleza, já que você conhece o Spring vamos ao assunto de hoje: como o Spring implementa o padrão de projeto <strong>M</strong>odel-<strong>V</strong>iew-<strong>C</strong>ontroller (<strong>MVC</strong>).</p>
<p>O MVC é um padrão de arquitetura de software que visa separar a lógica de negócio da lógica de apresentação, permitindo o desenvolvimento, teste e manutenção isolado de ambos (via <a href="http://pt.wikipedia.org/wiki/MVC" target="_blank">Wikipedia</a>).</p>
<p>A imagem acima descreve o fluxo das informações no padrão MVC:</p>
<p><strong>1</strong> &#8211; O usuário dispara um evento através da camada de <strong>visualização </strong>(clica em um botão na página ou algo do gênero);<br />
<strong>2</strong> &#8211; O controlador recebe o evento e coordena como as coisas vão acontecer do lado do servidor, ou seja, passa o fluxo para os objetos necessários para realizar a regra de negócio;<br />
<strong> 3</strong> &#8211; O modelo é utilizado para representar o domínio das informações do negócio então ele é chamado pelo controlador para a realizar a regra de negócio que deve ser realizada. O modelo pode ainda ser usado para enviar os dados para a visão (camada onde o usuário <strong>vê</strong> as coisas acontecerem, uma página web por exemplo);<br />
<strong> 4</strong> &#8211; Depois que o controlador realiza a regra de negócio utilizando o modelo ele renderiza a nova visão e a envia para o usuário.  Criar uma aplicação utilizando o padrão MVC nada mais é do que separar a lógica em &#8220;pacotes&#8221; (um que representa a interface com o usuário &#8211; <strong>visão</strong>, um que conterá o domínio da aplicação &#8211; <strong>modelo</strong>, e um que terá as classes responsáveis por controlar o fluxo da aplicação &#8211; <strong>controlador</strong>) e fazer com que as informações sigam um caminho certo.<br />
<br/><!--:--><span id="more-293"></span><!--:pt--></p>
<p style="text-align: left;">Após essa pequena introdução teórica vamos ver como o Spring implementa esse padrão:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/01/esquema_spring_mvc1.jpg"><img class="aligncenter size-full wp-image-303" title="esquema_spring_mvc" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/esquema_spring_mvc1.jpg" alt="" width="441" height="249" /></a><strong>Figura 1 &#8211; Fluxo de informações no Spring Web MVC</strong></p>
<p><strong>1</strong> &#8211; A requisição do usuário <strong>sempre</strong> chega em um único servlet, o Dispatcher Servlet. Esse é um padrão muito comum em frameworks MVC chamado <em>front controller</em> (controlador frontal) onde um único servlet é responsável por receber a requisição, delegar o processamento para os outros componentes da aplicação e devolver uma resposta para o usuário;<br />
<strong> 2</strong> &#8211; Uma vez que o Dispatcher Servlet tem a requisição ele precisa descobrir para qual <strong>controller</strong> essa requisição será enviada. Para isso ele pede ajuda para o Handler Mapping. Baseado na URL da requisição ele indica qual é o controlador a ser invocado;<br />
<strong> 3</strong> &#8211; A requisição é então enviada para o controlador que cuidará dos dados contidos nela. Uma vez que o controlador recebe a requisição ele processa os dados que ela trouxe e executa alguma regra do negócio da aplicação (faz uma venda, adiciona um novo produto no estoque, aluga um dvd, abre uma os, &#8230;);<br />
<strong> 4</strong> &#8211; Frequentemente a lógica processada pelo controlador resulta em alguma informação que deve ser levada de volta para o usuário (o <em><strong>model</strong></em>). Somente enviar a informação de volta não é o suficiente, ela deve ser formatada de um jeito que o usuário a entenda, para isso ela deve ser enviada para a <strong>view</strong>. Para isso o model e alguns dados da view são encapsulados em um objeto <em><strong>ModelAndView </strong></em>e retornados ao Dispatcher;<br />
<strong> 5</strong> &#8211; Como o controlador não fica preso a apenas uma view ele envia uma dica no objeto <em>ModelAndView </em>para o Dispatcher saber para qual view deve enviar os dados. O Dispatcher repassa essa dica para o ViewResolver que devolve qual view deve ser chamada;<br />
<strong> 6</strong> &#8211; Por fim o Dispatcher envia as informações (model) para a view (página JSP) que acabou de descobrir. A página renderiza as informações recebidas e é devolvida ao usuário.</p>
<p>Simples de entender, não!? <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Vamos por a mão na massa então! A IDE será o NetBeans 6.9.1. Crie uma nova Aplicação Web (Java Web &gt; Aplicação Web) e no último passo do assistente selecione o framework Spring Web MVC (<strong>Figura 2</strong>) e finalize.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2011/01/novo_projeto_framework1.jpg"><img class="aligncenter size-medium wp-image-298" title="novo_projeto_framework" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/novo_projeto_framework-300x180.jpg" alt="" width="300" height="180" /></a></p>
<p style="text-align: center;"><strong>Figura 2 &#8211; Incluir o framework Spring Web MVC no projeto</strong></p>
<p style="text-align: left;">O NetBeans já cria alguns arquivos para nós (legal ele né). Vamos dar uma analisada nos códigos que ele gerou.</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/01/pacote1.jpg"><img class="aligncenter size-full wp-image-308" title="pacote" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/pacote1.jpg" alt="" width="201" height="183" /></a><strong>Figura 3 &#8211; Arquivos gerados pelo NetBeans</strong></p>
<p style="text-align: left;">O arquivo de configuração do Dispatcher Servlet é o dispatcher-servlet.xml, nele são declarados todos os beans que o servlet precisa para conhecer os controladores e os outros componentes que o auxiliam no decorrer da aplicação.</p>
<p style="text-align: left;">Repare que o arquivo <strong>redirect.jsp</strong> é o único arquivo que fica fora do diretório WEB-INF. Isso é feito porque uma boa prática é que todas as views fiquem dentro do diretório WEB-INF para que só possam ser acessadas a partir do Dispatcher. O redirect.jsp apenas envia qualquer requisição feita na raiz da aplicação para a página index.jsp que está dentro do WEB-INF.</p>
<p style="text-align: left;">Para poder fazer esse redirecionamento é necessário que o fluxo explicado logo antes (6 passos) seja seguido. Para tal o NetBeans criou os seguintes beans no arquivo de configuração do Dispatcher:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;indexController&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.web.servlet.mvc.ParameterizableViewController&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">p:viewName</span>=<span style="color: #ff0000;">&quot;index&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p style="text-align: left;">O controlador que será responsável por uma requisição à página index.jsp. Como esse controlador não vai fazer nenhum processamento dos dados da requisição foi criado um controlador da classe <em>ParameterizableViewController</em> que o Spring Web MVC já tem implementado. O que ele faz é apenas repassar um <em>ModelAndView </em>informando o nome da view (informado no parâmetro <em>viewName</em>) para o Dispatcher.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;urlMapping&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;mappings&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;index.htm&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>indexController<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p style="text-align: left;">Quando é utilizado o ParameterizableViewController é necessário mapear quais URLs serão direcionadas para aquele controlador, por isso foi criado o bean <strong>urlMapping </strong>da classe <em>SimpleUrlHandlerMapping</em> que apenas linka a url &#8220;<strong>index.htm</strong>&#8221; ao controlador <strong>indexController</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;viewResolver&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">p:prefix</span>=<span style="color: #ff0000;">&quot;/WEB-INF/jsp/&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">p:suffix</span>=<span style="color: #ff0000;">&quot;.jsp&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p style="text-align: left;">O <strong>viewResolver</strong> é quem vai ajudar o Dispatcher a saber para qual view encaminhar o <em>ModelAndView </em>que o controlador retornar (passo 5 do fluxo ali em cima). Como no <em>ModelAndView </em>só vai ter o nome lógico da view (no caso da index vai ter apenas a String <strong>index</strong> que foi definida no controlador <strong>indexController</strong>), o que o viewResolver faz é criar o caminho da view utilizando o prefixo e sufixo informados na declaração do bean. Para descobrir o caminho da view <strong>index</strong> ele vai fazer:</p>
<p style="text-align: left;">&#8220;WEB-INF/jsp/&#8221; + &#8220;index&#8221; + &#8220;.jsp&#8221; =&gt; resultando em &#8220;WEB-INF/jsp/index.jsp&#8221;</p>
<p style="text-align: left;">E por fim o NetBeans criou um bean sem id:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p style="text-align: left;">Esse bean é o cara que vai analisar todas as outras URLs e mapeá-las para os nossos controladores. Isso vai ficar mais claro daqui a pouquinho quando fizermos o nosso controlador.</p>
<p style="text-align: left;">Bom, vamos a nossa aplicação então, vou utilizar a idéia de uma aplicação que tem no livro <strong>Use a Cabeça: Servlets &amp; JSP</strong>: uma aplicação que dá conselhos sobre cerveja! O usuário diz o tipo da cerveja que ele quer e nossa aplicação retorna alguns conselhos sobre quais cervejas ele poderia tomar. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p style="text-align: left;">Vamos aproveitar a estrutura que o NetBeans já criou e apenas alterar a página index.jsp para ser o nosso formulário onde o usuário vai indicar qual tipo de cerveja ele quer tomar:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
   &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&nbsp;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Cervejeiro Online&lt;/title&gt;
    &lt;/head&gt;
&nbsp;
    &lt;body&gt;
        &lt;h3&gt;Eu sou um cervejeiro profissional!&lt;/h3&gt;
        &lt;form action=&quot;sugestor.htm&quot; method=&quot;post&quot;&gt;
        &lt;p&gt;
            Qual tipo de cerveja você prefere?
            &lt;select name=&quot;tipo&quot;&gt;
                &lt;option value=&quot;pilsen&quot;&gt;Pilsen&lt;/option&gt;
                &lt;option value=&quot;chop&quot;&gt;Chop&lt;/option&gt;
                &lt;option value=&quot;malzbier&quot;&gt;Malzbier&lt;/option&gt;
            &lt;/select&gt;
        &lt;/p&gt;
        &lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Quer saber minha sugestão?&quot; /&gt;&lt;/p&gt;
        &lt;/form&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p style="text-align: left;">Quando o usuário pedir o conselho da nossa aplicação sobre cervejas do tipo que ele selecionou os dados serão enviados via POST para a URL <strong>sugestor.htm</strong>.</p>
<p style="text-align: left;">Lembra daquele bean que o NetBeans criou sem id (<em>ControllerClassNameHandlerMapping</em>)? Então, ele vai entrar em ação agora! Ele vai ser chamado pelo Dispatcher para identificar qual controlador vai receber a requisição.</p>
<p style="text-align: left;">O processo que esse bean utiliza para identificar qual controlador vai ser chamado é apenas pegar a String existente na URL até &#8220;.htm&#8221; e concatenar com &#8220;Controller&#8221;. Nesse caso o controlador que vai ser chamado é o SugestorController. Caso nosso formulário enviasse os dados para <strong>cervejeiro.htm</strong> o controlador que o Dispatcher tentaria invocar seria o <strong>Cervejeiro</strong>Controller. Facinho não? ^^</p>
<p style="text-align: left;">Sendo assim vamos construir o nosso controlador:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SugestorController <span style="color: #000000; font-weight: bold;">extends</span> AbstractController <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> SugestorService sugestor<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setSugestor<span style="color: #009900;">&#40;</span>SugestorService sugestor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">sugestor</span> <span style="color: #339933;">=</span> sugestor<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> ModelAndView handleRequestInternal<span style="color: #009900;">&#40;</span>HttpServletRequest request, HttpServletResponse response<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #003399;">String</span> tipo <span style="color: #339933;">=</span> request.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;tipo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        List<span style="color: #339933;">&lt;</span>cerveja<span style="color: #339933;">&gt;</span> sugestoes <span style="color: #339933;">=</span> sugestor.<span style="color: #006633;">sugerir</span><span style="color: #009900;">&#40;</span>tipo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        ModelAndView modelAndView <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ModelAndView<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;sugestao&quot;</span>, <span style="color: #0000ff;">&quot;cervejas&quot;</span>, sugestoes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> modelAndView<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: left;">Uma coisa que não podemos esquecer: para o Spring entender que essa nossa classe é um controlador ela deve herdar de AbstractController ou qualquer outra classe que represente um controlador para o Spring Web MVC (pode ver mais exemplos aqui na <a href="http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-controller" target="_blank">referência oficial</a>).</p>
<p style="text-align: left;">Uma boa prática no desenvolvimento de aplicativos MVC é nunca deixar toda a lógica dentro do controlador, usar ele apenas para delegar funções para outros componentes para que esses sim executem a lógica.</p>
<p style="text-align: left;">Para isso servem os famosos Services! Nosso controlador recebe um SugestorService (injetado pelo Spring) e delega para ele a função de sugerir as cervejas para o usuário.</p>
<p style="text-align: left;">Depois que o SugestorService retorna uma lista de cervejas (já já veremos a classe <em>Cerveja</em> que faz parte do <strong>model</strong> da nossa aplicação) para o controlador é hora de montar o <em>ModelAndView</em> que deve ser retornado para o Dispatcher.</p>
<p style="text-align: left;">Nosso<em> ModelAndView</em> foi instanciado com 3 parâmetros sendo o primeiro o nome da view (aquela dica que o bean <strong>viewResolver</strong> vai usar para montar o nome do arquivo lembra?), o segundo é o nome que a lista de cervejas terá na página JSP e o terceiro é a lista propriamente dita, quer dizer, quando formos mostrar as cervejas na página <strong>WEB-INF/jsp/sugestao.jsp </strong>(eu sei que você lembra como o viewResolver acha o arquivo da view, só escrevi ele ali pra você não esquecer mesmo.. hehehe) a lista terá o nome <strong>cervejas</strong>.</p>
<p style="text-align: left;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/02/controller_flow.jpg"><img class="aligncenter size-full wp-image-328" title="controller_flow" src="http://www.javasimples.com.br/wp-content/uploads/2011/02/controller_flow.jpg" alt="" width="563" height="88" /></a></p>
<p style="text-align: center;"><strong>Figura 4 &#8211; Fluxo de componentes que são executados para uma requisição (sem contar com a view)</strong></p>
<p style="text-align: left;">Com isso nosso controlador ficou muito bem projetado, recebe uma requisição, chama um Service para realizar a lógica de negócio da aplicação e devolve um ModelAndView para o Dispatcher. Exatamente o que se espera de um controlador: que ele controle os componentes necessários para a regra de negócio ser executada.</p>
<p style="text-align: left;">Vamos ver como o SugestorService funciona. Apenas um pequeno detalhe: SugestorService é uma interface que apenas diz que o Service que a implementar deve sugerir uma lista de cervejas a partir do tipo (é bom utilizar as interfaces! se você não tem esse costume passe a ter! Lendo os primeiros posts dessa série você vai entender porquê):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> SugestorService <span style="color: #009900;">&#123;</span>
    List<span style="color: #339933;">&lt;</span>cerveja<span style="color: #339933;">&gt;</span> sugerir<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> tipo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: left;">Agora vejamos como esse Service funciona mesmo através do SugestorServiceImpl:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SugestorServiceImpl <span style="color: #000000; font-weight: bold;">implements</span> SugestorService <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>cerveja<span style="color: #339933;">&gt;</span> sugerir<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> tipo<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>cerveja<span style="color: #339933;">&gt;</span> cervejasSugeridas <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>cerveja<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>tipo.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;pilsen&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            cervejasSugeridas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Skol&quot;</span>, <span style="color: #cc66cc;">600</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            cervejasSugeridas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Antartica&quot;</span>, <span style="color: #cc66cc;">600</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>tipo.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;chop&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            cervejasSugeridas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Brahma&quot;</span>, <span style="color: #cc66cc;">600</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>tipo.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;malzbier&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            cervejasSugeridas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Brahma Malzbier&quot;</span>, <span style="color: #cc66cc;">355</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            cervejasSugeridas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Caracu&quot;</span>, <span style="color: #cc66cc;">355</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> cervejasSugeridas<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Cerveja criarCerveja<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome, <span style="color: #003399;">Integer</span> quantidade<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Cerveja cerveja <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cerveja<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cerveja.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span>nome<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cerveja.<span style="color: #006633;">setQuantidade</span><span style="color: #009900;">&#40;</span>quantidade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> cerveja<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: left;">Apenas verificamos qual o tipo que o usuário selecionou e montamos uma lista de cervejas a partir dele (desculpe se não gosta das que coloquei, juro que tentei ser bem simples e eclético).</p>
<p style="text-align: left;">A classe que representa nosso modelo é um simples POJO com o nome e a quantidade (em mls) da cerveja:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Cerveja <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> quantidade<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getNome<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> nome<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setNome<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nome</span> <span style="color: #339933;">=</span> nome<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getQuantidade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> quantidade<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setQuantidade<span style="color: #009900;">&#40;</span><span style="color: #003399;">Integer</span> quantidade<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">quantidade</span> <span style="color: #339933;">=</span> quantidade<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: left;">Bom, com toda a regra de negócio implementada vamos para a página que vai mostrar as cervejas sugeridas pela nossa aplicação (sugestao.jsp):</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
    &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&nbsp;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Minha Sugestão&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h3&gt;Eu acho que você deveria experimentar:&lt;/h3&gt;
        &lt;p&gt;
            &lt;c:forEach items=&quot;${cervejas}&quot; var=&quot;cerveja&quot;&gt;
                &lt;li&gt;
                    &lt;c:out value=&quot;${cerveja.nome}&quot;/&gt; -
                    &lt;c:out value=&quot;${cerveja.quantidade}&quot;/&gt;ml
                &lt;/li&gt;
            &lt;/c:forEach&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;a href=&quot;index.htm&quot;&gt;Voltar&lt;/a&gt;
        &lt;/p&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p style="text-align: left;">Apenas percorremos a lista de cervejas exibindo-as na tela (lembrando que o nome da lista é <strong>cervejas </strong>pois foi esse o nome que foi passado no ModelAndView lá no Controller).</p>
<p style="text-align: left;">Para fazermos nossa aplicação rodar precisamos apenas declarar o SugestorController e o SugestorServiceImpl no arquivo de configuração do Dispatcher Servlet:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;sugestorService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.javasimples.cervejeiro.service.impl.SugestorServiceImpl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;sugestorController&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;br.javasimples.cervejeiro.controller.SugestorController&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;sugestor&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;sugestorService&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p style="text-align: left;">Prontinho!! Simples códigos não? Só com essas pequenas classes nós construímos um Sugestor de Cervejas MVC!!! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p style="text-align: left;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/02/final1.jpg"><img class="aligncenter size-medium wp-image-333" title="final1" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/final1-300x157.jpg" alt="" width="300" height="157" /></a></p>
<p style="text-align: center;"><strong><a href="http://www.javasimples.com.br/wp-content/uploads/2011/02/final1.jpg"></a>Figura 5 &#8211; Escolhendo um tipo e pedindo a opinião da aplicação</strong></p>
<p style="text-align: left;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/02/final2.jpg"><img class="aligncenter size-medium wp-image-334" title="final2" src="http://www.javasimples.com.br/wp-content/uploads/2011/01/final2-300x156.jpg" alt="" width="300" height="156" /></a></p>
<p style="text-align: center;"><strong>Figura 6 &#8211; Cerveja sugerida pela aplicação</strong></p>
<p style="text-align: left;">Espero que com esse pequeno tutorial e essa pequena aplicação você tenha entendido (pelo menos um pouco) o padrão MVC e como ele torna nossa aplicação muito bem estruturada. Dê uma olhada como os pacotes do meu projeto ficaram bem separados:</p>
<p style="text-align: center;"><a href="http://www.javasimples.com.br/wp-content/uploads/2011/02/pacotes.jpg"><img class="aligncenter size-full wp-image-336" title="pacotes" src="http://www.javasimples.com.br/wp-content/uploads/2011/02/pacotes.jpg" alt="" width="255" height="434" /></a><strong>Figura 7 &#8211; Hierarquia de pastas e pacotes da aplicação</strong></p>
<p style="text-align: left;">Caso queira pegar o projeto fique a vontade para baixá-lo por <a href="http://dl.dropbox.com/u/4918828/SpringMVCJavaSimples.rar" target="_blank">aqui</a>.</p>
<p style="text-align: left;">Apenas um último conselho antes de encerrarmos este post: o que foi apresentado aqui foi a estrutura mais básica possível do Spring Web MVC, apenas com o que vimos você consegue fazer uma aplicação de pequeno porte porém eu aconselho fortemente você procurar aprender mais sobre o framework antes de utilizá-lo no desenvolvimento do seu projeto de graduação (hehehe).</p>
<p style="text-align: left;">O Spring Web MVC contém muitos (muitos mesmo!) outros beans que facilitam muito a vida do desenvolvedor! Vale mesmo a pena dar uma procurada por fontes mais avançadas. Um livro bem didático é o <strong>Spring in Action 2</strong> (Craig Walls, 2008) e a <a href="http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html" target="_blank"><strong>referência </strong></a>é incrível!</p>
<p style="text-align: left;">Até a próxima!</p>
<p style="text-align: left;">[]s,<br />
Saab.</p>
<p><!--:--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/spring-2/spring-framework-parte-5-spring-web-mvc/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Spring Security 3 -&gt; Deixando sua aplicação Web segura!</title>
		<link>http://www.javasimples.com.br/spring-2/spring-security-3-deixando-sua-aplicacao-web-segura</link>
		<comments>http://www.javasimples.com.br/spring-2/spring-security-3-deixando-sua-aplicacao-web-segura#comments</comments>
		<pubDate>Tue, 19 Oct 2010 15:46:00 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[aplicacao]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[segura]]></category>
		<category><![CDATA[sprigngsource]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[suite]]></category>
		<category><![CDATA[tool]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=250</guid>
		<description><![CDATA[Continuando com o assunto dos posts anteriores, vamos falar sobre mais uma vantagem do Spring Framework: o Spring Security. O Spring Security antes era conhecido como Acegi Security pois era um projeto paralelo ao Spring Framework e aos poucos foi integrado a ele. Quando eu digo &#8216;integrado&#8217; eu quero dizer que ele (Acegi Security) continuou [...]]]></description>
			<content:encoded><![CDATA[<p><!--:pt--><a href="http://www.javasimples.com.br/wp-content/uploads/2010/09/spring_security_login1.jpg"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/09/spring_security_login1.jpg" alt="" title="spring_security" width="360" height="208" class="aligncenter size-full wp-image-251" /></a></p>
<p>Continuando com o assunto dos posts anteriores, vamos falar sobre mais uma vantagem do Spring Framework: o Spring Security.</p>
<p>O Spring Security antes era conhecido como Acegi Security pois era um projeto paralelo ao Spring Framework e aos poucos foi integrado a ele. Quando eu digo &#8216;integrado&#8217; eu quero dizer que ele (Acegi Security) continuou sendo desenvolvido baseado no Spring, ou seja, ele funciona perfeitamente sobre o container do Spring. Há algum tempo o nome do projeto foi alterado para Spring Security pois ele acabou entrando para a família do Spring (péssimo trocadilho não&#8230; <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<p>Mesmo com a integração, quando você baixa o Spring Framework o Spring Security não está incluído. Precisamos baixá-lo separadamente.</p>
<p>O Spring Security utiliza uma biblioteca externa para logging das suas funções e essa biblioteca também não vem no download do projeto, portanto temos que baixar o Apache Commons Logging também.</p>
<p>Apenas mais um detalhe: se você acompanhou os posts anteriores sobre o Spring Framework você notou que a versão do framework era a 2.5 (que vem nativamente com o NetBeans 6.8), porém neste post eu já irei utilizar a mais nova versão: 3.0 pois o Spring Security 3.0 (versão melhor e mais fácil de usar do que a anterior) só roda em cima do Spring Framework 3.0.</p>
<p>Ahh, vou trocar a IDE também, ao invés de utilizar o NetBeans eu irei utilizar o SpringSource Tool Suite (Eclipse que o pessoal da SpringSource deu uma turbinada para facilitar a vida de quem usa o Spring).</p>
<p>Seguem os links para os downloads necessários:</p>
<ul>
<li><a target="_blank" href="http://s3.amazonaws.com/dist.springframework.org/release/SPR/spring-framework-3.0.4.RELEASE.zip"> Spring Framework 3.0</a></li>
<li><a target="_blank" href="http://s3.amazonaws.com/dist.springframework.org/release/SEC/spring-security-3.0.3.RELEASE.zip">Spring Security 3.0</a></li>
<li><a target="_blank" href="http://ftp.unicamp.br/pub/apache//commons/logging/binaries/commons-logging-1.1.1-bin.zip">Apache Commons Logging 1.1.1</a></li>
<li><a target="_blank" href="http://www.springsource.com/landing/best-development-tool-enterprise-java">SpringSource Tool Suite (caso queira conhecer a ferramenta)</a></li>
</ul>
<p><!--:--><span id="more-250"></span><!--:pt--></p>
<p><br/>Nosso escopo para a aplicação: teremos dois tipos de usuários na aplicação: Funcionários e Gerentes. Os funcionários tem acesso apenas à área restrita a funcionários e os gerentes tem acesso tanto à área de funcionários (mesmo sendo gerentes eles também são funcionários poxa) quanto à área restrita aos gerentes.</p>
<p>A autenticação será baseada nos dados contidos em uma tabela no banco de dados, então para o usuário possuir acesso ele deve estar cadastrado no banco de dados.</p>
<p><strong>OBS: Também será necessário fazer o download do driver JDBC para a conexão com o banco de dados que você for utilizar. Eu irei utilizar o MySQL, caso você também use ele pode pegar o driver <a href="http://www.mysql.com/downloads/connector/j/" target="_blank">aqui</a>.</strong></p>
<p>Nossa tabela que conterá os dados dos usuários será essa:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #ff0000;">`users`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`username`</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`password`</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">40</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`authority`</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_unicode_ci <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span>  <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`username`</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Os campos só estão em inglês porque eu fiquei com preguiça de mudar para português, desculpem.. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Com o banco de dados pronto nós já podemos por a mão na massa!</p>
<p>Criei um novo projeto (Dynamic Web Project) no STS (SpringSource Tool Suite) chamado <strong>ControleAcesso</strong> e a primeira coisa que fiz foi incluir as dependências no classpath, ou seja, todos os .jar encontrados na pasta <strong>/dist</strong> dos releases do Spring Framework e do Spring Security e também o .jar do Apache Commons Logging e o .jar o driver JDBC do MySQL:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_dependencias11.jpg"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_dependencias1-300x205.jpg" alt="" title="spring_security_dependencias" width="300" height="205" class="aligncenter size-medium wp-image-260" /></a></p>
<p>OBS: Adicionei também os .jar referentes a JSTL para poder utilizá-la nos JSPs.</p>
<p><strong>Estrutura da Aplicação</strong><br />
Agora vou criar a estrutura básica de arquivos para a nossa aplicação:</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_estrutura_arquivos1.jpg"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_estrutura_arquivos1.jpg" alt="" title="spring_security_estrutura_arquivos" width="287" height="362" class="aligncenter size-full wp-image-259" /></a></p>
<p>Uma estrutura bem básica onde nós podemos ver que as páginas que estão na raiz da aplicação são as páginas de login, index e uma responsável por mostrar uma mensagem de acesso negado caso o usuário tente acessar uma página que não pode.</p>
<p>OBS: Essa é a estrutura final da aplicação, chegaremos até ela aos poucos durante o decorrer do post.</p>
<p>Depois existem mais duas pastas (funcionario e gerente) representando as partes da aplicação que somente usuários autenticados podem acessar. Nestas pastas eu coloquei apenas um index para confirmar que tivemos acesso ou não a página.</p>
<p>Vamos começar a ver as páginas então:</p>
<p>index.jsp (raíz):</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
	&lt;title&gt;Home Page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Página de Boas Vindas&lt;/h1&gt;
	&lt;a href=&quot;./funcionario&quot;&gt;Área de Funcionários&lt;/a&gt;
	&lt;br/&gt;
	&lt;a href=&quot;./gerente&quot;&gt;Área de Gerentes&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>A página inicial da aplicação apenas dá as boas vindas ao usuário e mostra os possíveis caminhos para ele: área de funcionários ou área de gerentes.</p>
<p>funcionario/index.jsp</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
	&lt;title&gt;Área do Funcionário&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Bem Vindo a Área do Funcionário&lt;/h1&gt;
	&lt;a href=&quot;../index.jsp&quot;&gt;Retornar para a Página Inicial&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>gerente/index.jsp</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
	&lt;title&gt;Área do Gerente&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Bem Vindo a Área do Gerente&lt;/h1&gt;
	&lt;a href=&quot;../index.jsp&quot;&gt;Retornar para a Página Inicial&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Pronto, esta é a estrutura básica da aplicação, caso você rode ela agora você vai conseguir navegar livremente pelas áreas que devem ser restritas (funcionários e gerentes).</p>
<p><strong>Adicionando o Spring na aplicação</strong><br />
Próximo passo é por o Spring para funcionar nessa nossa aplicação. Como as bibliotecas já estão no classpath então vamos criar o arquivo de configuração do Spring: dentro da pasta WEB-INF crie um xml chamado &#8220;<strong>applicationContext</strong>&#8220;.</p>
<p>Caso esteja usando o STS basta clicar com o botão direito na pasta WEB-INF, ir em <em>New </em>e depois em <em>Other</em>. Vá na pasta <em>Spring</em> e selecione <em>Spring Bean Configuration File</em>, na proxima janela digite o nome (applicationContext) e na proxima janela você pode escolher os namespaces que quer usar no arquivo então deixe selecionado os seguintes: <strong>beans </strong> e <strong>sec</strong>. Quando selecionar o <strong>sec</strong> você ainda deve especificar o XSD do Spring Framework 3.0. Fazendo isso a IDE já vai criar a estrutura básica do arquivo de configuração com todos os namespaces. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_arquivo_conf1.jpg"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/10/spring_security_arquivo_conf1.jpg" alt="" title="spring_security_arquivo_conf" width="527" height="622" class="aligncenter size-full wp-image-271" /></a></p>
<p>O applicationContext.xml deve ficar parecido com este (já vou adiantar um detalhe e declarar o dataSource responsável por se comunicar com o banco de dados onde está a tabela com os usuários e suas autenticações):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span> <span style="color: #000066;">xmlns:sec</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/security&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #808080; font-style: italic;">&lt;!-- data source --&gt;</span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;driverClassName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;com.mysql.jdbc.Driver&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;jdbc:mysql://localhost/spring_security&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;username&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;root&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;123&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Para concluir esta etapa basta fazer uma pequena modificação no <strong>web.xml</strong> para adicionar um listener que o Spring tem para facilitar nossa vida. Sempre que a aplicação vai começar a funcionar esse listener procura pelo arquivo applicationContext.xml e carrega o Spring e os beans e configurações definidos nesse arquivo.</p>
<p>OBS: Tem como configurar o listener para receber uma lista com o nome de vários arquivos de configuração (caso você goste de separar as configurações em arquivos separados) e então ele carrega todos, porém esse é um assunto para outro post (ou uma rápida busca no google <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ).</p>
<p>Basta adicionar a seguinte tag no <strong>web.xml</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.context.ContextLoaderListener<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/listener<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>OK, caso você execute a aplicação agora e ficar atento às mensagens de LOG você irá ver o Spring carregando e o dataSource sendo configurado, ou seja, tudo indo bem até aqui!</p>
<p>Aliás, verá também que você consegue facilmente acessar as áreas que deveriam ser restritas. Tudo certo até aqui.</p>
<p><strong>Adicionando segurança na aplicação</strong><br />
Vamos começar a fazer algumas modificações para podermos adicionar a segurança na nossa aplicação.</p>
<p>Primeiro de tudo vamos adicionar um novo filtro no nosso <strong>web.xml</strong>. Esse filtro será responsável por interceptar todas as requisições à aplicacão, verificar se o usuário possui acesso e liberar a requisição normalmente ou então mostrar um erro.</p>
<p>Segue o XML necessário para a declaração e configuração do filtro:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.springframework.web.filter.DelegatingFilterProxy<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>A partir de agora todas as requisições serão interceptadas pelo Spring, só falta deixar bem claro para o Spring Security quem pode fazer o que na aplicação.</p>
<p>Antes de continuar com o processo de autenticação de usuários nós precisamos ter o usuários concorda? hehehe<br />
Vou adicionar agora dois usuários para nossa aplicação: um gerente e um funcionário comum.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> users<span style="color: #66cc66;">&#40;</span>username<span style="color: #66cc66;">,</span>password<span style="color: #66cc66;">,</span>authority<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'func'</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">'func'</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">'ROLE_FUNC'</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> users<span style="color: #66cc66;">&#40;</span>username<span style="color: #66cc66;">,</span>password<span style="color: #66cc66;">,</span>authority<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'ger'</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">'ger'</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">'ROLE_GER'</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Agora já temos o usuário <strong>func </strong>e o usuário <strong>ger </strong>para poder testar na nossa aplicação.</p>
<p>Repare que o atributo <em>authority </em>foi preenchido com <strong>ROLE_FUNC </strong>e <strong>ROLE_GER</strong>. Isso ocorre porque o Spring Security sempre busca um prefixo no tipo de autorização de cada usuário e o padrão é este (&#8220;ROLE_&#8221;). Logo mais mostrarei como trocar para um prefixo a sua escolha como &#8220;FUNCAO_&#8221;, &#8220;AUTH_&#8221; ou o que você quiser.</p>
<p>Continuando: toda a autenticação será feita com a declaração de apenas dois beans no <strong>applicationContext.xml</strong>. Vamos ao primeiro:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:http</span> <span style="color: #000066;">auto-config</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:form-login</span> <span style="color: #000066;">login-page</span>=<span style="color: #ff0000;">&quot;/login.jsp&quot;</span> <span style="color: #000066;">authentication-failure-url</span>=<span style="color: #ff0000;">&quot;/login.jsp?erro=invalido&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/funcionario/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_FUNC,ROLE_GER&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/gerente/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_GER&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;IS_AUTHENTICATED_ANONYMOUSLY&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:http<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>OBS: O prefixo das tags dos Spring Security é &#8220;sec&#8221; pois foi o namespace declarado para ele na tag root <beans>: <strong>xmlns:sec=&#8221;&#8230;&#8221;</strong></p>
<p>A tag <http> serve para definir os parâmetros básicos para o Spring Security saber o que fazer com as requisições. O atributo <strong>auto-config</strong> nos poupa de definir todas as tags necessárias para o funciomento correto, sendo assim, só precisamos nos focar no que realmente faz parte da nossa aplicação, como o que eu coloquei: formulário de login e URL&#8217;s que serão interceptadas.</p>
<p>Cada tag < intercept-url > identifica uma URL ou um padrão de URL&#8217;s e qual a permissão o usuário deve ter para acessar tal (tais) URL (s).<br />
A primeira tag diz que todas as URL&#8217;s que comecem com &#8220;/funcionario/&#8221; só poderão ser acessadas por usuários que tiverem autorização ROLE_FUNC ou ROLE_GER.<br />
Já a segunda restringe o acesso a todas URL&#8217;s que comecem com &#8220;/gerente/&#8221; para usuários que estiverem autorizados com ROLE_GER.<br />
E a última tag define que qualquer outra URL que ainda não foi definida anteriormente pode ser acessada sem autenticação nenhuma.</p>
<p>Na tag < form-login> foram definidos alguns atributos meio básicos: <strong>login-page</strong> informando qual é a página de login e <strong>authentication-failure-url</strong> informando qual é a página que será exibida caso o login falhe (neste caso eu coloquei a mesma página de login e apenas enviei um parâmetro via GET para podermos saber quando ocorre o erro).</p>
<p>Segue a página de login e como deve ser o formulário:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot; %&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&nbsp;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Autenticação&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;c:if test=&quot;${param.erro ==  'invalido'}&quot;&gt;
            Usuário e/ou senha inválidos!&lt;br/&gt;&lt;br/&gt;
        &lt;/c:if&gt;
&nbsp;
        &lt;form action=&quot;j_spring_security_check&quot; method=&quot;post&quot;&gt;
            Usuário: &lt;input type=&quot;text&quot; name=&quot;j_username&quot; /&gt;&lt;br /&gt;
            Senha: &lt;input type=&quot;text&quot; name=&quot;j_password&quot;&gt;&lt;br /&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Efetuar Login&quot;&gt;
        &lt;/form&gt;
        &lt;br /&gt;&lt;br /&gt;
        &lt;a href=&quot;index.jsp&quot;&gt;Retornar para a Página Inicial&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Caso a página seja carregada com o parâmetro &#8220;erro&#8221; contendo o valor &#8220;invalido&#8221; então um erro será mostrado (fiz usando JSTL). E o formulário de login deve ser enviado para a URL &#8220;j_spring_security_check&#8221; passando como parâmetros o nome de usuário (j_username) e a senha (j_password). Esses nomes são padrões do Spring Framework e bem fáceis de serem seguidos.</p>
<p>O processo de login é simples assim e encerra as explicações sobre o primeiro bean responsável pela segurança de nossa aplicação.</p>
<p>Vamos ao próximo bean:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:jdbc-user-service</span> <span style="color: #000066;">data-source-ref</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">users-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, password, 'true' as enable FROM users WHERE username=?&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">authorities-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, authority FROM users WHERE username=?&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Dentro do < authentication-manager > é onde especificamos onde o Spring Security deve buscar os dados para verificar se um usuário está autenticado ou não. Como já tinhamos previsto desde o começo do post que iríamos fazer a autenticação através do banco de dados, utilizamos a tag < jdbc-user-service-data-source > passando o dataSource que conecta no banco que contém nossos usuários.</p>
<p>Quando o Spring Security tenta autenticar um usuário com dados vindos de um banco de dados ele possui um padrão: para cada usuário devem ser retornados 3 campos: username, password e enable, sendo eles usuário, senha e o último dizendo se o usuário está habilitado ou não.</p>
<p>Para não ficarmos presos no padrão de tabelas que o Spring Security sugere para usuários, nós podemos escrever quais querys ele irá utilizar para recuperar os dados que ele precisa.</p>
<p>O atributo <strong>users-by-username-query</strong> deve trazer os dados do usuário (username, password e enabled) selecionado pelo nome de usuário e o atributo <strong>authorities-by-username-query</strong> deve trazer o nome de usuário e o tipo de autenticação (username, authority) também selecionado pelo nome de usuário.</p>
<p>Com essa flexibilidade de configuração é possível utilizar qualquer estrutura de tabelas responsável por armazenar os usuários.</p>
<p>E pronto! Agora nossa aplicação web já possui um mecanismo de segurança para restringir o acesso apenas a usuários autenticados! Executando a aplicação agora você verá que só consegue acessar a área de funcionários autenticando-se como um funcionário ou gerente, exatamente como havíamos configurado. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>Mudar o prefixo do tipo de autorização</strong><br />
Para mudar o prefixo padrão (ROLE_) podemos setar o atributo <strong>role-prefix</strong> da tag < jdbc-user-service-data-source >.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:jdbc-user-service</span> <span style="color: #000066;">data-source-ref</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span>  <span style="color: #000066;">role-prefix</span>=<span style="color: #ff0000;">&quot;TIPO_&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">users-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, password, 'true' as enable FROM users WHERE username=?&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">authorities-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, authority FROM users WHERE username=?&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Com essa configuração os prefixos devem ser &#8220;TIPO_&#8221;. Ex de tipos de autorização: TIPO_GERENTE e TIPO_FUNCIONARIO.</p>
<p><strong>Logout</strong><br />
Para o usuário efetuar logout no sistema basta acessar a URL &#8220;<strong>j_spring_security_logout</strong>&#8221; na raiz da aplicação.</p>
<p>Ex: para colocar um link &#8220;Sair&#8221; na página /funcionario/index.jsp devemos colocar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;a href=&quot;../j_spring_security_logout&quot;&gt;Sair&lt;/a&gt;.</pre></div></div>

<p>Porque a url deve ser acessada na raiz da aplicação web: /Aplicacao/j_spring_security_logout e não /Aplicacao/funcionario/j_spring_security_logout.</p>
<p><strong>Acesso Negado</strong><br />
Caso o usuário logado como funcionário queira acessar a seção restrita a gerentes ele irá receber uma página de erro bem estranha (que o servidor de aplicativos gera). Para mostrar uma página mais amigável avisando que o usuário não tem acesso a uma certa área basta preencher o atributo <strong>access-denied-page</strong> da tag < http >.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:http</span> <span style="color: #000066;">auto-config</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000066;">access-denied-page</span>=<span style="color: #ff0000;">&quot;/negado.jsp&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:form-login</span> <span style="color: #000066;">login-page</span>=<span style="color: #ff0000;">&quot;/login.jsp&quot;</span> <span style="color: #000066;">authentication-failure-url</span>=<span style="color: #ff0000;">&quot;/login.jsp?erro=invalido&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/funcionario/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_FUNC,ROLE_GER&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/gerente/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_GER&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;IS_AUTHENTICATED_ANONYMOUSLY&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:http<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>negado.jsp:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Acesso Negado&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Acesso Negado&lt;/h1&gt;
        &lt;a href=&quot;../index.jsp&quot;&gt;Página Inicial&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p><strong>Encriptação da senha</strong><br />
Caso queira que a senha seja protegida por algum algoritmo de encriptação basta adicionar uma nova tag no authentication-manager:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:password-encoder</span> <span style="color: #000066;">hash</span>=<span style="color: #ff0000;">&quot;md5&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sec:jdbc-user-service</span> <span style="color: #000066;">data-source-ref</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span>  <span style="color: #000066;">role-prefix</span>=<span style="color: #ff0000;">&quot;TIPO_&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">users-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, password, 'true' as enable FROM users WHERE username=?&quot;</span></span>
<span style="color: #009900;">            <span style="color: #000066;">authorities-by-username-query</span>=<span style="color: #ff0000;">&quot;SELECT username, authority FROM users WHERE username=?&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-provider<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sec:authentication-manager<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Neste caso o algoritmo usado é o MD5, poderia ser o MD4, SHA, entre outros.</p>
<p>Para inserir o usuário com uma senha criptografada com MD5 no MySQL fica assim:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> users<span style="color: #66cc66;">&#40;</span>username<span style="color: #66cc66;">,</span>password<span style="color: #66cc66;">,</span>authority<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'func'</span><span style="color: #66cc66;">,</span>MD5<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'func'</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">'ROLE_FUNC'</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p><strong>Exibindo partes da página apenas para usuários autorizados</strong><em> UPDATE(19/03/2011)</em></p>
<p>Respondendo a pergunta que nosso leitor <strong>Gerson</strong> postou nos comentários vamos ver como podemos restringir partes da página com base na autorização que o usuário possui.</p>
<p>A primeira coisa a fazer é ter certeza de que a biblioteca <strong>spring-security-taglibs-3.x.x.jar</strong> está no classpath da aplicação.</p>
<p>Depois temos que importar as taglibs do Spring Security na página onde queremos usá-la e então utilizá-las de fato. <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html">Referência das taglibs do Spring Security</a>.</p>
<p>Eu alterei a página /funcionario/index.jsp para mostrar uma mensagem de boas vindas somente para os usuários que possuem a autorização ROLE_GER:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@ taglib prefix=&quot;sec&quot; uri=&quot;http://www.springframework.org/security/tags&quot; %&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
        &lt;title&gt;Área do Funcionário&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Bem Vindo a Área do Funcionário&lt;/h1&gt;
&nbsp;
        &lt;sec:authorize ifAnyGranted=&quot;ROLE_GER&quot;&gt;
            Bem vindo gerente &lt;sec:authentication property=&quot;principal.username&quot; /&gt;.
        &lt;/sec:authorize&gt;
&nbsp;
        &lt;br/&gt;&lt;br/&gt;
        &lt;a href=&quot;../j_spring_security_logout&quot;&gt;Sair&lt;/a&gt;.&lt;br/&gt;
        &lt;a href=&quot;../index.jsp&quot;&gt;Retornar para a Página Inicial&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Fácil de ler e de fazer não é? <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><br />
Só para explicar melhor, o que utilizamos foram as tags <em>authorize</em> e <em>authentication</em>.</p>
<p><strong>authorize</strong>: tudo o que estiver dentro esta tag só irá ser rendererizado caso a autorização do usuário logado atenda a regra de algum atributo que informarmos. Neste exemplo usei o atributo <em>ifAnyGranted</em>, quer dizer que o conteúdo da tag só irá ser renderizado caso o usuário logado possua alguma das autorizações (ROLEs) informadas no atributo.</p>
<p>Para informar mais de uma autorização basta separá-las por vírgula.<br />
Ex: ifAnyGranted=&#8221;ROLE_GER,ROLE_FUNC&#8221;.<br />
Neste caso o conteúdo da tag será renderizado caso o usuário possua autorização ROLE_GER ou ROLE_FUNC.</p>
<p>Outros possíveis atributos são: <em>ifAllGranted</em> (somente irá renderizar caso o usuário possua todas as autorizações informadas) e <em>ifNotGranted </em>(irá renderizar somente se o usuário não possuir a autorização informada).</p>
<p><strong>authentication</strong>: utilizada para recuperar o objeto <em>Authentication </em>que está guardado no contexto do Spring Security. O usuário logado é guardado na propriedade <em><strong>principal </strong></em>do objeto <em>Authentication</em>, sendo assim nós podemos exibir seu nome de usuário através do atributo <em>property </em>informando <strong>principal.username</strong>.</p>
<p>Obs: os dados do usuário logado são guardados em um objeto que implementa a interface <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/UserDetails.html"><em>UserDetails</em></a>, ou seja, o atributo <em><strong>principal </strong></em>do objeto <em>Authentication </em>é uma implementação de <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/UserDetails.html"><em>UserDetails</em></a>.<br />
<br/></p>
<p>E chegamos ao final de mais um post.<br />
O projeto do STS está disponível para download <a href="http://dl.dropbox.com/u/4918828/ControleAcesso.rar">aqui</a>.</p>
<p>A seção de comentários está aberta para feedback e dúvidas pessoal, fiquem a vontade. =]</p>
<p>Até a proxima,<br />
Saab.<!--:--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/spring-2/spring-security-3-deixando-sua-aplicacao-web-segura/feed</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>

