<?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 &#187; annotations</title>
	<atom:link href="http://www.javasimples.com.br/tag/annotations/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>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 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 2 -&gt; Aspect Oriented Programming</title>
		<link>http://www.javasimples.com.br/spring-2/spring-framework-parte-2-aspect-oriented-programming</link>
		<comments>http://www.javasimples.com.br/spring-2/spring-framework-parte-2-aspect-oriented-programming#comments</comments>
		<pubDate>Wed, 11 Aug 2010 19:53:43 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[advice]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspect]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[aspectos]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[joinpoint]]></category>
		<category><![CDATA[orientada]]></category>
		<category><![CDATA[oriented]]></category>
		<category><![CDATA[poa]]></category>
		<category><![CDATA[pointcut]]></category>
		<category><![CDATA[programacao]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/?p=193</guid>
		<description><![CDATA[Considerações iniciais: se vc veio ler este post e ainda não leu o post anterior (Spring Framework Parte 1 -> Dependency Injection), por favor o faça! Caso contrário você pode não entender os códigos utilizados aqui. Beleza, daqui pra frente vou assumir que você já sabe como linkar os beans no Spring utilizando o arquivo [...]]]></description>
			<content:encoded><![CDATA[<p><!--:pt-->Considerações iniciais: se vc veio ler este post e ainda <strong>não</strong> leu o post anterior (<a target="_blank" href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-1-dependency-injection/">Spring Framework Parte 1 -> Dependency Injection</a>), por favor o faça! Caso contrário você pode não entender os códigos utilizados aqui.</p>
<p>Beleza, daqui pra frente vou assumir que você já sabe como linkar os beans no Spring utilizando o arquivo de configuração (pelo menos o básico, como visto na <a target="_blank" href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-1-dependency-injection/">Parte 1</a> desta série).</p>
<p>Vamos ao nosso post então: <strong>AOP: Aspect Oriented Programming (POA: Programação Orientada a Aspectos)</strong>. E como sempre, pra fugir um pouco dos termos técnicos, vamos a uma história:</p>
<p>Imagine que você está desenvolvendo um e-commerce, atualmente está desenvolvendo o checkout do teu sistema, ou seja, o cliente já escolheu tudo o que ele queria, e agora vai fazer a transferência eletrônica do pagamento (vamos imaginar que você está desenvolvendo tudo isso). Olhando com um nível de abstração muito alto o seu código poderia ser algo assim:<br />
<!--:--><span id="more-193"></span><!--:pt--></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> CheckoutService <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//...</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> efetuarPagamento<span style="color: #009900;">&#40;</span>Carrinho carrinho<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        LOGGER.<span style="color: #006633;">log</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: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; - Executando efetuarPagamento(Carrinho carrinho)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>carrinho.<span style="color: #006633;">getCliente</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">temPermissao</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>
             DAO.<span style="color: #006633;">iniciarTransacao</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;">try</span> <span style="color: #009900;">&#123;</span>
                 carrinho.<span style="color: #006633;">getCliente</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">debitar</span><span style="color: #009900;">&#40;</span>carrinho.<span style="color: #006633;">getValorTotal</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                 carrinho.<span style="color: #006633;">finalizarCompra</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                 DAO.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                 LOGGER.<span style="color: #006633;">log</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: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; - Pagamento efetuado!&quot;</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;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                 DAO.<span style="color: #006633;">rollback</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                 LOGGER.<span style="color: #006633;">log</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: #006633;">toString</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: #339933;">+</span> e.<span style="color: #006633;">toString</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: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            LOGGER.<span style="color: #006633;">log</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: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Cliente não está autenticado&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>
    <span style="color: #666666; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Dê uma boa olhada no código&#8230; O que tem a ver mesmo com o checkout são apenas as linhas:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">carrinho.<span style="color: #006633;">getCliente</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">debitar</span><span style="color: #009900;">&#40;</span>carrinho.<span style="color: #006633;">getValorTotal</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
carrinho.<span style="color: #006633;">finalizarCompra</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O resto é código responsável por logging, controle de transação, permissão de acessos, coisas que são necessárias porém que ocupam muito espaço, &#8220;sujam&#8221; o código. A idéia da orientação a objetos é encapsular em um objeto todas as coisas referentes a ele, os serviços que ele vai prestar, e não ficar poluindo ele com outros códigos que não tem nada a ver com o seu propósito.</p>
<p>Mas esses códigos são necessários para a aplicação funcionar corretamente! O que fazer então? <strong>Orientação a Aspectos!!!</strong></p>
<p>A Orientação a Aspectos surgiu exatamente para eliminar os <em>cross-cutting concerns</em> (código que é necessário, porém foge das preocupações principais do objeto, como no caso acima, o checkout tem que se preocupar com o logging, transação e permissão).</p>
<p>OBS: Existem vários termos técnicos, sem graça, e difíceis de entender envolvidos nesse &#8220;paradigma&#8221; de programação. Nós vamos discutindo-os conforme o tutorial for andando.</p>
<p>Então como eu faço para separar esse código chato dos meus objetos? A Orientação a Aspectos funciona assim:</p>
<p><strong>-></strong> Primeiro a gente separa o código que não tem nada a ver com o nosso objeto (logging, transação, permissão e tals) em um lugar separado. Esse lugar separado se chama <em><strong>advice</strong></em> (é o <em>o que</em>).</p>
<p><strong>-></strong> Ainda dentro do advice, é definido onde o programa tem que dar uma &#8220;paradinha&#8221; para que o código que foi separado possa ser executado. Todo lugar que o programa pode dar essa &#8220;paradinha&#8221; é chamado de <em><strong>join point</strong></em>. Um <em>join point</em> pode ser por exemplo: uma chamada de método, a execução de um método, instanciação de objetos, execução de construtores, e mais alugns (é o <em>quando</em>).</p>
<p><strong>-></strong> Uma vez que nós já sabemos <em>o que</em> vai ser feito (advice) e <em>quando</em> vai ser feito (join point), falta definir <em>onde</em> vai ser feito. Para isso servem os <em>pointcuts</em>. Geralmente são definidos utilizando os nomes das classes e métodos que queremos interceptar, mas também podem ser definidos através de expressões regulares (logo mais veremos um exemplo na prática).</p>
<p><strong>-></strong> Por fim, o conjunto de tudo isso (o que vai ser feito, quando vai ser feito e onde vai ser feito) é chamado de <em><strong>aspect (aspecto)</strong></em>.</p>
<p>Em <del datetime="2010-08-11T17:28:59+00:00">muito</del> poucas palavras isso é a base da orientação a aspectos. Vamos ver como a gente pode utilizar isso no Spring.</p>
<p>O Spring oferece diversos tipos de suporte a Orientação a Aspectos (eles foram evoluindo através das versões), dentre eles o suporte para a orientação a aspectos declarativa (no XML de configuração) e anotativa (utilizando annotations (se não sabe o que são annotations <a target="_blank" href="http://www.javasimples.com.br/mundo-java/annotations-o-que-pra-que-serve/">clique aqui</a>)).</p>
<p>Eu estudei as duas e devo dizer que me identifiquei muito mais com a orientação a aspectos utilizando annotations, portanto é ela que eu irei mostrar aqui (caso queira aprender sobre o outro tipo eu aconselho fortemente o livro Spring in Action 2 (Manning, 2008), capítulo 4).</p>
<p>OBS: Eu irei reaproveitar o código da <a target="_blank" href="http://www.javasimples.com.br/mundo-java/spring-framework-parte-1-dependency-injection/">Parte 1</a>, então caso você não tenha feito o tutorial anterior eu aconselho a pelo menos pegar os código de lá. Tudo o que eu fiz foi renomear o projeto para &#8220;OrientacaoAspectos&#8221;, o pacote principal para &#8220;orientacaoaspectos&#8221; e todas as definições dos beans no arquivo de configuração para bater com o novo nome do pacote.<br />
Como o suporte de orientação a aspectos do Spring consegue usar a poderosa linguagem do AspectJ (para definir pointcuts) nós vamos usá-la aqui, para tanto é necessário o download da biblioteca do AspectJ e a inclusão dela no classpath. O arquivo pode ser baixado <a target="_blank"  href="http://www.eclipse.org/aspectj/downloads.php">no site do projeto</a>.<br />
Só mais um detalhe: o arquivo que vc baixa do site eh um .jar chamado: aspectj-x.x.x.jar, dentro dele é que estão as bibliotecas que o Spring precisa, então abra este arquivo com o WinRAR (ou outro do gênero) navegue até a pasta /lib, extraia os .jar que estão lá e os adicione ao classpath.</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2010/08/orientacao_aspectos_aspectj1.png"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/08/orientacao_aspectos_aspectj1.png" alt="" title="orientacao_aspectos_aspectj" width="650" height="352" class="aligncenter size-full wp-image-204" /></a></p>
<p>Voltando ao escopo da nossa aplicação: o show de talentos Ídolos Spring, vamos adicionar um requisito muito importante para qualquer programa de entrenimento: a platéia!</p>
<p>Sem utilizar a orientação a aspectos nós teríamos os seguintes códigos:</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> Plateia <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Plateia<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> sentar<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;A platéia está sentando&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> desligarCelulares<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;A platéia está desligando os celulares&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> aplaudir<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;CLAP CLAP CLAP UHULL CLAP CLAP&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> vaiar<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;UUUUUU!! E FORA! E FORA! UUUUU!! &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>


<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> Cantor <span style="color: #000000; font-weight: bold;">implements</span> Competidor <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Musica musica<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Plateia plateia<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Cantor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> setMusica<span style="color: #009900;">&#40;</span>Musica musica<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;">musica</span> <span style="color: #339933;">=</span> musica<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> setPlateia<span style="color: #009900;">&#40;</span>Plateia plateia<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;">plateia</span> <span style="color: #339933;">=</span> plateia<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> apresentar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        plateia.<span style="color: #006633;">sentar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        plateia.<span style="color: #006633;">desligarCelulares</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;">try</span> <span style="color: #009900;">&#123;</span>
            musica.<span style="color: #006633;">cantar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            plateia.<span style="color: #006633;">aplaudir</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><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            plateia.<span style="color: #006633;">vaiar</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: A platéia estaria sendo injetada na classe Cantor pelo container assim como está acontecendo com a musica.</p>
<p>Sem a orientação a aspectos, toda classe que implemente a interface Competidor tem que ficar se preocupando com a platéia. Não é certo o competidor ficar mostrando os assentos para a platéia, pedir para elas desligarem os celulares, se apresentar e por fim pedir para eles aplaudirem ou vaiarem. Isso é coisa que a platéia tem que fazer sozinha!</p>
<p>Vamos utilizar todo o poder da orientação a aspectos para que a platéia consiga fazer isso sozinha. A classe Cantor volta a ser o que era antes, se preocupando somente em cantar a sua musica:</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> Cantor <span style="color: #000000; font-weight: bold;">implements</span> Competidor <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Musica musica<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Cantor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> setMusica<span style="color: #009900;">&#40;</span>Musica musica<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;">musica</span> <span style="color: #339933;">=</span> musica<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> apresentar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        musica.<span style="color: #006633;">cantar</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>E a classe Plateia vai ser &#8220;anotada&#8221; para utilizar as funcionalidades da orientação a aspectos:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Aspect
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Plateia <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Plateia<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
    @Pointcut<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;execution(* *.apresentar(..))&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apresentacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
&nbsp;
    @Before<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;apresentacao()&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sentar<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;A platéia está sentando&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Before<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;apresentacao()&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> desligarCelulares<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;A platéia está desligando os celulares&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @AfterReturning<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;apresentacao()&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> aplaudir<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;CLAP CLAP CLAP UHULL CLAP CLAP&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @AfterThrowing<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;apresentacao()&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> vaiar<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;UUUUUU!! E FORA! E FORA! UUUUU!! &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>Aconteceram algumas coisas aqui:</p>
<p>-> Primeiro de tudo, a classe foi anotada com a anotação <em>@Aspect</em> indicando o óbvio: esta classe será um aspecto;</p>
<p>-> Depois foi criado um método que não faz absolutamente nada chamado <strong>apresentacao()</strong> cujo único propósito deste método é ser anotado para se &#8220;tornar&#8221; um pointcut (&#8220;tornar&#8221; entre aspas porque apresentar() continua sendo um método que não faz nada, apenas contém uma anotação que é um pointcut).<br />
    O parâmetro passado para a anotação <em>@Pointcut</em> é uma frase na linguagem de descrição de pointcuts do AspectJ. Segue uma pequena explicação dela (que eu acabei de fazer no Paint!! hehehe):</p>
<p><a href="http://www.javasimples.com.br/wp-content/uploads/2010/08/orientacao_aspectos_aspectj_sintaxe_pointcut1.png"><img src="http://www.javasimples.com.br/wp-content/uploads/2010/08/orientacao_aspectos_aspectj_sintaxe_pointcut1.png" alt="" title="orientacao_aspectos_aspectj_sintaxe_pointcut" width="650" height="352" class="aligncenter size-full wp-image-206" /></a></p>
<p>-> Depois que o pointcut está definido, basta anotar os métodos desejados especificando quando e onde eles devem ser executados. Para especificar onde os métodos serão executados é utilizado o nome do método que está anotado com o pointcut (no nosso exemplo é a string &#8220;apresentacao()&#8221;) e para especificar quando existem algumas outras anotações. Creio que as mais utilizadas são: <em>@Before</em>, <em>@AfterReturning</em> e <em>@AfterThrowing</em> (caso queira saber quais são as outras, fique a vontade para fuçar na <a target="_blank" href="http://www.eclipse.org/aspectj/doc/next/aspectj5rt-api/org/aspectj/lang/annotation/package-tree.html">documentação</a>).</p>
<p>E voilá, nosso aspecto está pronto! Para ele funcionar só falta mais uma coisinha, que não é tão pequena assim (pelo menos na teoria, na prática é sim! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ).</p>
<p>Para a orientação a aspectos funcionar devem ser criadas cópias dos objetos que queremos interceptar. Tais cópias contém os advices (códigos das cross-cut concerns) e esse objeto é que recebe as requisições, executa os advices e depois passa a requisição para o método do objeto original. Essas cópias de objetos que contém os advices são chamados de Proxy (no plural: Proxies).</p>
<p>E até algumas versões atrás os proxies tinham que ser criados na mão!!! Imagine que trabalho que dava&#8230; Porém o Spring provê um mecanismo automático para a criação dos proxies (ufa!).</p>
<p>Segue o arquivo de configuração para podermos fazer nosso exemplo 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:aop</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/aop&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-2.0.xsd</span>
<span style="color: #009900;">            http://www.springframework.org/schema/aop</span>
<span style="color: #009900;">            http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
       <span style="color: #808080; font-style: italic;">&lt;!-- competidores --&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;atireiopau&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.AtireiOPauNoGato&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;jose&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.Cantor&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;musica&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;atireiopau&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;ciranda&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.CirandaCirandinha&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;gaita&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.Gaita&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;piano&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.Piano&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;carlos&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;orientacaoaspectos.CantorTocador&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;musica&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;atireiopau&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;instrumento&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;piano&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: #808080; font-style: italic;">&lt;!-- platéia --&gt;</span>
       <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;orientacaoaspectos.Plateia&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;aop:aspectj-autoproxy</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 style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Três coisas novas apareceram no arquivo de configuração:</p>
<p>1 &#8211; Na root tag (<beans>) foi definido mais um namespace (xmlns:aop) e na localização dos esquemas estão os seus respectivos links. Isso é necessário para o arquivo de configuração saber quais tags podem e quais não podem quando o assunto é AOP;</p>
<p>2 &#8211; Foi declarado o bean correspondente à platéia. Ele não tem o atributo id definido porque provavelmente nós nunca precisaremos de uma referência à platéia, eles fazem tudo sozinhos! Não tem porque darmos um id para a platéia sendo que nunca iremos utilizá-la;</p>
<p>3 &#8211; A simples tag &#8220;< aop:aspectj-autoproxy />&#8221; já diz para o Spring fazer todo o trabalho duro de ficar criando os proxies para nós.</p>
<p>E é isso caro leitor(a) (será que mulher le isso? to brincando!! hehehe), agora é só compilar (in the java-way of course), pedir pra tia VM executar e ver a platéia trabalhando sozinha, que povo educado! <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Saindo da historinha e voltando ao mundo real, é extremamente fácil prover um mecanismo de log simples e que pode sofrer modificações facilmente utilizando a programação orientada a aspectos. Suponha que sua aplicação utilize o mecanismo padrão de log do Java e queira mudar para o Log4J: simples! Basta ir no seu aspecto responsável pelo log, e alterar os códigos. Você só tem trabalho uma vez (e nem é tanto trabalho assim)!</p>
<p>Nos próximos posts veremos os mecanismos que o Spring provê para banco de dados, transações, segurança, e mais alguns. Tão fácil quanto um System.out.println(&#8220;Hello World&#8221;).</p>
<p>Quem quiser o código do projeto, está <a href="http://dl.dropbox.com/u/4918828/OrientacaoAspectos.rar">aqui</a>.</p>
<p>[]s e até a próxima,<br />
Saab.<!--:--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/spring-2/spring-framework-parte-2-aspect-oriented-programming/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Annotations: O que é, pra que serve?</title>
		<link>http://www.javasimples.com.br/core-java/annotations-o-que-pra-que-serve</link>
		<comments>http://www.javasimples.com.br/core-java/annotations-o-que-pra-que-serve#comments</comments>
		<pubDate>Fri, 02 Apr 2010 14:33:01 +0000</pubDate>
		<dc:creator>Felipe Saab</dc:creator>
				<category><![CDATA[Core Java]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[exemplo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.javasimples.com.br/mundo-java/annotations-o-que-pra-que-serve/</guid>
		<description><![CDATA[Annotations… recurso interessante. Sempre tive a curiosidade de saber como funcionavam, então fui perguntar pro Google. Pretendo demonstrar aqui o que eu aprendi nas minhas pesquisas. Annotations são… advinhem… anotações! É um jeito que você tem de fazer alguma marcação em um atributo, método, classe, entre outros. Elas sempre devem ser digitadas antes do objeto [...]]]></description>
			<content:encoded><![CDATA[<p><!--:pt-->
<p>Annotations… recurso interessante. </p>
<p>Sempre tive a curiosidade de saber como funcionavam, então fui perguntar pro Google. <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />     <br />Pretendo demonstrar aqui o que eu aprendi nas minhas pesquisas.</p>
<p>Annotations são… advinhem… anotações! É um jeito que você tem de fazer alguma marcação em um atributo, método, classe, entre outros.</p>
<p>Elas sempre devem ser digitadas antes do objeto que você queira anotar (método, atributo…) e o nome das anotações são sempre precedidos de @ (arroba). Ex:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@MinhaAnotacao
<span style="color: #000000; font-weight: bold;">class</span> MinhaClasse<span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
  <br />Até ai tudo bem, mas você deve estar se perguntando: “Pra que diabos eu vou usar isso? Pra que ficar enfeitando meu código?”. Calma. Tudo tem seu propósito.</p>
<p><!--:--><span id="more-136"></span><!--:pt--></p>
<p>Para poder trabalhar com as anotações, iremos utilizar a reflexão computacional, portanto sugiro que você leitor, leia meus posts antigos sobre Reflexão Computacional:</p>
<p><a href="http://www.javasimples.com.br/mundo-java/java-e-seus-espelhos-reflexo-computacional/" target="_blank">Java e seus Espelhos: Reflexão Computacional</a> e</p>
<p><a href="http://javasimples.wordpress.com/2010/02/08/reflexo-computacional-exemplo-prtico/" target="_blank">Reflexão Computacional: Exemplo Prático</a></p>
<p>Daqui pra frente vou supor que você entende e sabe utilizar a reflexão computacional…</p>
<hr />
<p align="center"><strong>Exemplo 1: Testando seus métodos</strong></p>
<hr />
<p>Então vamos lá: imagine que você é um bom programador com uma ótima noção de engenharia de software (o que realmente deve ser verdade neh… <img src='http://www.javasimples.com.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ). Você sabe que uma fase importante no desenvolvimento de um software é a fase de testes. Porém você não gosta dos frameworks existentes para teste unitário (ou qualquer outro tipo), então você decide criar o seu próprio!</p>
<p>Para não ficar muito chato de utilizar, você decide que durante o desenvolvimento, todo método que possuir a anotação “@Testar” será testado pelo seu framework.</p>
<p>OK, com essa idéia na cabeça vamos criar a nossa anotação @Testar:</p>
<p>Testar.java<br />
  </p>

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

<p></p>
<p>Reparem que a nossa anotação deve ser anotada com <em>meta-anotações</em>. </p>
<p>A anotação @Retention(RetentionPolicy.RUNTIME) diz que a VM deve manter essas anotações em tempo de execução para podermos ler elas através da reflexão. Outras opções seriam: SOURCE e CLASS.</p>
<p>E a anotação @Target(ElementType.METHOD) indica que a nossa anotação só é aplicada a métodos. Outras opções seriam: FIELD, TYPE (classe e interface), PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, e PACKAGE.</p>
<p>Reparem que para declarar a nossa própria anotação, deve-se utilizar “@interface” antes do nome da anotação.</p>
<p>Pronto! Só isso! É assim que as anotações são criadas. Uma vez que já temos ela, vamos criar a classe que irá ser testada.</p>
<p>ClasseParaTestar.java<br />
  </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> ClasseParaTestar <span style="color: #009900;">&#123;</span>
&nbsp;
    @Testar
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> metodo1<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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Deu zebra!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Testar
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> metodo2<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Testar
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> metodo3<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> metodo4<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Testar
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> metodo5<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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Ixi maria... Erro!&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> metodo6<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Testar
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> metodo7<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> metodo8<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p></p>
<p>Como o propósito é só demonstrar as anotações, os métodos não fazem nada.</p>
<p>Beleza, agora os métodos que eu quero testar já estão “anotados”. Vamos criar a classe principal do nosso framework de testes.</p>
<p>Testador.java<br />
  </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> Testador <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> testar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Class<span style="color: #339933;">&lt;?&gt;</span> classe <span style="color: #339933;">=</span> obj.<span style="color: #006633;">getClass</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> passou <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> falhou <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</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;-------------Inicio dos Testes--------------&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><span style="color: #003399;">Method</span> m <span style="color: #339933;">:</span> classe.<span style="color: #006633;">getDeclaredMethods</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>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>m.<span style="color: #006633;">isAnnotationPresent</span><span style="color: #009900;">&#40;</span>Testar.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">print</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Testando o método: &quot;</span><span style="color: #339933;">;</span> <span style="color: #339933;">+</span> m.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    m.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    passou<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; =&gt; passou!&quot;</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;">Throwable</span> t<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    falhou<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; =&gt; falhou! &quot;</span> <span style="color: #339933;">+</span> t.<span style="color: #006633;">getCause</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>
        <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;---------------Fim dos Testes---------------&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;Passaram: &quot;</span> <span style="color: #339933;">+</span> passou <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;, Falharam: &quot;</span> <span style="color: #339933;">+</span> falhou<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></p>
<p>Simples simples (caso você entenda a reflexão)… Tudo o que a gente faz é verificar se o método possui a anotação @Testar, caso ele possua, o método é invocado. Se não ocorrer nenhuma exceção, então ele passou no teste, caso contrário ele falhou.</p>
<p>Para utilizar o nossa pequeno (micro) framework, basta chamar o método estático passando um objeto da nossa classe para testar:<br />
  </p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Testador.<span style="color: #006633;">testar</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ClasseParaTestar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p></p>
<p>Para o nosso exemplo, você deve obter a seguinte saída:<br />
  </p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">-------------Inicio dos Testes--------------
Testando o método: metodo1 =&gt; falhou! java.lang.RuntimeException: Deu zebra!
Testando o método: metodo2 =&gt; passou!
Testando o método: metodo3 =&gt; passou!
Testando o método: metodo5 =&gt; falhou! java.lang.RuntimeException: Ixi maria... Erro!
Testando o método: metodo7 =&gt; passou!
---------------Fim dos Testes---------------
Passaram: 3, Falharam: 2</pre></div></div>

<p>
  </p>
<p>Obs: Eu tirei este exemplo da <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html" target="_blank">documentação oficial</a>.</p>
</p>
<hr />
<p align="center"><strong>Exemplo 2: Validando seus atributos</strong></p>
<hr />
<p>Vamos criar uma classe genérica que faz a validação dos atributos de qualquer classe que você peça para ele validar. É claro que os atributos a serem validados devem possuir as anotações que nós vamos criar.</p>
<p>Vamos criar as nossas anotações então: @ValidarContemTexto e @ValidarPositivo.</p>
<p>ValidarPositivo.java<br />
  </p>

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

<p></p>
<p>ValidarContemTexto.java<br />
  </p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
@Target<span style="color: #009900;">&#40;</span>ElementType.<span style="color: #006633;">FIELD</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> ValidarContemTexto <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span> min<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p></p>
<p>Opa! Apareceu uma coisa nova aqui. A anotação @ValidarContemTexto possui um atributo???</p>
<p>É isso mesmo! As anotações podem conter atributos para realizar alguma lógica durante o processamento delas. </p>
<p>No nosso caso, a anotação @ValidarContemTexto irá validar se o atributo que está decorado com a anotação possui pelo menos <strong>min</strong> caracteres (que por default é 1).</p>
<p>Reparem que a meta-anotação @Target é ElementType.FIELD, porque vamos utilizar essas anotações para decorar atributos.</p>
<p>A classe Usuario para o nosso teste será a seguinte:</p>
<p>Usuario.java<br />
  </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> Usuario <span style="color: #009900;">&#123;</span>
&nbsp;
    @ValidarContemTexto<span style="color: #009900;">&#40;</span>min <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> login<span style="color: #339933;">;</span>
&nbsp;
    @ValidarContemTexto<span style="color: #009900;">&#40;</span>min <span style="color: #339933;">=</span> <span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> senha<span style="color: #339933;">;</span>
&nbsp;
    @ValidarPositivo
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> nivel<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//Construtores, getters e setters</span>
    <span style="color: #666666; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O login deverá possuir pelo menos 10 caracteres, a senha deverá possuir pelo menos 20 caracteres (para garantir alguma segurança… hehehe) e o nível deverá ser um inteiro positivo maior ou igual a zero.</p>
<p>Vamos ver a classe responsável pela validação:</p>
<p>Validador.java<br />
  </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> Validador <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;">boolean</span> validar<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Class<span style="color: #339933;">&lt;?&gt;</span> classe <span style="color: #339933;">=</span> obj.<span style="color: #006633;">getClass</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;">boolean</span> ok <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> f <span style="color: #339933;">:</span> classe.<span style="color: #006633;">getDeclaredFields</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>
            f.<span style="color: #006633;">setAccessible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">//Annotation @ValidarPositivo</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>f.<span style="color: #006633;">isAnnotationPresent</span><span style="color: #009900;">&#40;</span>ValidarPositivo.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><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: #000066; font-weight: bold;">int</span> num <span style="color: #339933;">=</span> <span style="color: #003399;">Integer</span>.<span style="color: #006633;">parseInt</span><span style="color: #009900;">&#40;</span>f.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toString</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: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>num <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        ok <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
                        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Exception</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> t<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>f.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; deve ser um valor inteiro positivo.&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>
&nbsp;
            <span style="color: #666666; font-style: italic;">//Annotation @ValidarContemTexto</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>f.<span style="color: #006633;">isAnnotationPresent</span><span style="color: #009900;">&#40;</span>ValidarContemTexto.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                ValidarContemTexto anotacao <span style="color: #339933;">=</span> f.<span style="color: #006633;">getAnnotation</span><span style="color: #009900;">&#40;</span>ValidarContemTexto.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003399;">String</span> texto <span style="color: #339933;">=</span> f.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</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: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>texto.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> anotacao.<span style="color: #006633;">min</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>
                        ok <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</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>f.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; deve possuir pelo menos &quot;</span> <span style="color: #339933;">+</span> anotacao.<span style="color: #006633;">min</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; caracteres.&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> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Throwable</span> t<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>f.<span style="color: #006633;">getName</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: #339933;">+</span> t.<span style="color: #006633;">getCause</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>
        <span style="color: #000000; font-weight: bold;">return</span> ok<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p></p>
<p>Quase igual ao exemplo anterior, porém nós percorremos os atributos (getDeclaredFields()) ao invés do métodos (getDeclaredMethods()).</p>
<p>Um if para cada anotação… nada muito novo. A única novidade aqui é a recuperação da anotação @ValidarContemTexto para poder acessar o valor que foi definido para o seu atributo <strong>min</strong>. Mas também não é nada de outro mundo.</p>
<p>O código a seguir cria 3 usuários e executa a validação com cada um deles:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ArrayList<span style="color: #339933;">&lt;</span>usuario<span style="color: #339933;">&gt;</span> usuarios <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>usuario<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
usuarios.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Usuario<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;login&quot;</span>, <span style="color: #0000ff;">&quot;senha&quot;</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
usuarios.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Usuario<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;felipesaab&quot;</span>, <span style="color: #0000ff;">&quot;SaabRocks&quot;</span>, <span style="color: #339933;">-</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
usuarios.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Usuario<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;javasimples&quot;</span>, <span style="color: #0000ff;">&quot;javasimplesjavasimples&quot;</span>, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Usuario u <span style="color: #339933;">:</span> usuarios<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;Validando usuario: &quot;</span> <span style="color: #339933;">+</span> u.<span style="color: #006633;">getLogin</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: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>Validador.<span style="color: #006633;">validar</span><span style="color: #009900;">&#40;</span>u<span style="color: #009900;">&#41;</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;Usuário OK.&quot;</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: #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;Corrija os erros.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</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: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p></p>
<p>O resultado será o seguinte:<br />
  </p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">Validando usuario: login
login deve possuir pelo menos 10 caracteres.
senha deve possuir pelo menos 20 caracteres.
Corrija os erros.
&nbsp;
Validando usuario: felipesaab
senha deve possuir pelo menos 20 caracteres.
nivel deve ser um valor inteiro positivo.
Corrija os erros.
&nbsp;
Validando usuario: javasimples
Usuário OK.</pre></div></div>

<p>&#160;</p>
<p>Chegamos ao fim de mais um post aqui do Java Simples. Espero que tenham gostado, eu pelo menos achei esse assunto interessantíssimo.</p>
<p>Quem quiser pode pegar os arquivos que eu fiz e testei <a href="http://dl.dropbox.com/u/4918828/AppAnnotations.rar" target="_blank">aqui</a>.</p>
<p>[]s e até a próxima,<br />
  <br />Saab. </p>
<p><!--:--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javasimples.com.br/core-java/annotations-o-que-pra-que-serve/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

