<?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>Spring Art Work</title>
	<atom:link href="http://www.springartwork.es/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.springartwork.es</link>
	<description></description>
	<lastBuildDate>Tue, 17 Nov 2009 11:37:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>es</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Spring + JBoss Seam ¿amor imposible?</title>
		<link>http://www.springartwork.es/2009/11/spring-jboss-seam-%c2%bfamor-imposible/</link>
		<comments>http://www.springartwork.es/2009/11/spring-jboss-seam-%c2%bfamor-imposible/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 10:30:11 +0000</pubDate>
		<dc:creator>Néstor Tarin</dc:creator>
				<category><![CDATA[JBoss]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://springartwork.s2grupo.es/?p=49</guid>
		<description><![CDATA[¿Son spring y seam frameworks incompatibles? ¿puedo aprovechar las ventajas que me ofrecen ambos en mis aplicaciones? Supongo que no seré el único que se plantea estas preguntas   En un proyecto interno sobre seam se nos planteó un grave problema, ¿cómo manejo de forma transparente y sencilla las transacciones distribuidas de mi aplicación? [...]]]></description>
			<content:encoded><![CDATA[<p>¿Son <a href="http://www.springsource.org/">spring</a> y <a href="http://www.jboss.com/products/seam/">seam</a> frameworks incompatibles? ¿puedo aprovechar las ventajas que me ofrecen ambos en mis aplicaciones? Supongo que no seré el único que se plantea estas preguntas <img src='http://www.springartwork.es/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  En un proyecto interno sobre seam se nos planteó un grave problema, ¿cómo manejo de forma transparente y sencilla las transacciones distribuidas de mi aplicación? ¿tengo que implementar un manejador de transacciones propio? ¿qué problemas puede darme? ¿es escalable esta solución? Al final, buceando por la documentación de seam encontré como integrarlo con spring y me dió paso a implementar la solución que andaba buscando <img src='http://www.springartwork.es/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Al principio optamos por una solución sencilla, la transacción de <a href="https://www.hibernate.org/">Hibernate</a> englobará a la transacción de <a href="http://jackrabbit.apache.org/">JackRabbit</a> de la siguiente manera:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">hibernateSession.<span style="color: #006633;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">try</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Bloque operaciones Hibernate</span>
    jackrabbitSession.<span style="color: #006633;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #666666; font-style: italic;">// Bloque operaciones Jackrabbit</span>
    jackrabbitSession.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    hibernateSession.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</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><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    hibernateSession.<span style="color: #006633;">rollbackTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>El código parece bueno pero es muy poco escalable. ¿Que sucedería si jackrabbit se nos queda pequeño y necesitamos utilizar otro <a href="http://en.wikipedia.org/wiki/Content_repository_API_for_Java">JCR</a> como puede ser <a href="http://www.alfresco.com/es/">Alfresco</a>?, muy simple, aparte de cambiar la arquitectura de la aplicación deberíamos de cambiar todos los DAOs lo que nos llevaría a resignarnos y continuar con la implementación actual. Esta solución fue descartada por su escasa escalabilidad.</p>
<p><strong>“Si la solución no es buena, ¿Qué hacemos?”</strong></p>
<p>La solución pasa por la<strong> propagación de las transacciones</strong> de ambos sistemas utilizando un manejador de transacciones que hable el mismo idioma (<a href="http://en.wikipedia.org/wiki/Java_Transaction_API">JTA</a>) y un framework que nos proporcione una cómoda integración (spring).</p>
<p>En el caso que nos ocupaba, nuestro servicio de negocio realiza el salvado de una nueva entidad en la BBDD y en el gestor de contenidos utilizando dos transacciones separadas, con lo cual ninguna de ellas conoce el estado de la otra y si en algún caso alguna de ellas realiza un <em>rollback</em>  la otra no sería consciente de ello. Este problema puede resultar bastante traumático debido a que puede crear inconsistencias entre los datos almacenados en la BBDD y el gestor de contenidos.</p>
<p>Es por ello necesario englobar las dos transacciones en una y así poder controlar el estado de éstas y realizar las operaciones oportunas si alguna de ellas falla.</p>
<p>Seam posee un módulo de integración con spring bastante bueno y muy fácil de utilizar.<br />
Para realizar la integración necesitamos los paquetes:</p>
<ul>
<li><strong><a href="http://seamframework.org/Download">jboss-seam-ioc</a></strong>: Modulo de integración entre los frameworks seam y spring</li>
<li><strong><a href="http://www.springsource.org/download">spring</a></strong>: Framework spring completo</li>
<li><strong><a href="http://www.springsource.org/download">aspectjweaver</a></strong>: Modulo de aspectj para la configuración de aspectos en spring (tx-advise)</li>
<li><strong><a href="http://www.springsource.org/download">cglib-nodep</a></strong>: Modulo de generación de código en tiempo de ejecución utilizado por spring en la creación de los proxis que envuelven las clases.</li>
</ul>
<p>El primer paso para configurar la integración de seam con spring es incluir el contexto de spring en el de seam añadiendo las siguientes líneas en el archivo components.xml:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;spring:context-loader</span> <span style="color: #000066;">config-locations</span>=<span style="color: #ff0000;">&quot;/WEB-INF/applicationContext.xml&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/spring:context-loader<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transaction:no-transaction</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>En el primer nodo declaramos la localización del fichero de configuración de spring y en el segundo delegamos el control de las transacciones a spring al deshabilitarlas en seam.</p>
<p>El siguiente paso es realizar la configuración de spring creando el archivo  xml “applicationContext.xml”:<br />
Espacios de nombres utilizados:</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;beans</span></span>
<span style="color: #009900;"><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;">xmlns:tx</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/tx&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:seam</span>=<span style="color: #ff0000;">&quot;http://jboss.com/products/seam/spring-seam&quot;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;</span>
<span style="color: #009900;">http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd</span>
<span style="color: #009900;">http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd</span>
<span style="color: #009900;">http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd</span>
<span style="color: #009900;">http://jboss.com/products/seam/spring-seam http://jboss.com/products/seam/spring-seam-2.1.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span></pre></div></div>

<p>El único a destacar es<strong> xmlns:seam</strong> el cual se utilizará para declarar un bean de spring como componente seam y poderlo inyectar en los demas componentes de la aplicación.</p>
<p>Para poder englobar las transacciones que ocurran en nuestra aplicación en la transacción controlada por Jboss es necesaria la creación de conectores <a href="http://en.wikipedia.org/wiki/Java_EE_Connector_Architecture">JCA</a> compatibles con Jboss. Estos conectores serán expuestos por el servidor de aplicaciones para ser utilizados desde nuestro entorno mediante la búsqueda por el nombre <a href="http://en.wikipedia.org/wiki/Jndi">JNDI</a>.<br />
<a href="http://www.jboss.org/jbossas/">Jboss 5.1</a> posee un “desplegador” de fuentes de datos, solamente debemos de crear archivos *-ds.xml utilizando el <em>dtd</em> <strong>http://www.jboss.org/j2ee/dtd/jboss-ds_1_5.dtd</strong> y dejarlos en el directorio de despliegue. Este <em>dtd</em> posee la definición para configurar la transaccion a utilizar en nuestra fuente de datos.</p>
<p>Los archivos de configuración de fuentes de datos para Jboss serían:<br />
<a href="http://en.wikipedia.org/wiki/Jdbc"><strong>JDBC</strong></a>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;datasources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local-tx-datasource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jndi-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>myJdbcDS<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jndi-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;driver-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.postgresql.Driver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/driver-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;connection-url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:postgresql://localhost:myPsqlPort/myDDBB<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/connection-url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;user-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>myUser<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/user-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>myPwd<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transaction-isolation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>TRANSACTION_SERIALIZABLE<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/transaction-isolation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/local-tx-datasource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/datasources<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><strong>JackRabbit</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;connection-factories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tx-connection-factory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jndi-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>myJcrRepo<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jndi-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;xa-transaction</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rar-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jackrabbit-jca-1.5.6.rar<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/rar-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;connection-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>javax.jcr.Repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/connection-definition<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;config-property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;homeDir&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;java.lang.String&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>myRepoLocation
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/config-property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;config-property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;configFile&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;java.lang.String&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>myRepo.xml
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/config-property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;config-property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;bindSessionToTransaction&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;java.lang.Boolean&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;/config-property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;application-managed-security</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tx-connection-factory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/connection-factories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Al no ser un conector común, debemos decirle a Jboss que paquete <em>“.rar”</em> utilizar y la clase que lo implementa<em> “javax.jcr.Repository”</em>. El paquete  <a href="http://archive.apache.org/dist/jackrabbit/1.5.6/binaries/">jackrabbit-jca-1.5.6.rar</a> lo pondremos dentro de la carpeta de despliegue.</p>
<p>Antes de arrancar el servidor de aplicaciones y ver que nuestros conectores están accesibles, es necesario copiar las librerias de jackrabbit y sus dependencias dentro del directorio “lib” del servidor que vamos a utilizar (comúnmente $JBOSS_HOME/server/default/lib)</p>
<p>Configuraremos Hibernate utilizando spring y obtendremos la fuente de datos utilizando JNDI. La configuración completa quedaría:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;jdbcXaDataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jndi.JndiObjectFactoryBean&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;jndiName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;java:myJdbcDs&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;hibernateSession&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.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;jdbcXaDataSource&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;mappingResources&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>hbm/myFile.hbm.xml<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;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Para poder configurar el repositorio de JackRabbit desde spring, es necesario utilizar la librería <a href="https://springmodules.dev.java.net/">springmodules-jcr</a>. Como en el caso de Hibernate, la fuente de datos la obtendremos por JNDI desde el servidor de aplicaciones. La configuración quedaría:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;repositoryCFB&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.jndi.JndiObjectFactoryBean&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;jndiName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;java:myJcrRepo&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;jcrCredentials&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;javax.jcr.SimpleCredentials&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;">index</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;admin&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;">index</span>=<span style="color: #ff0000;">&quot;1&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;">factory-bean</span>=<span style="color: #ff0000;">&quot;jcrCredentialsPassword&quot;</span> <span style="color: #000066;">factory-method</span>=<span style="color: #ff0000;">&quot;toCharArray&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 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>
<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;jcrCredentialsPassword&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;java.lang.String&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;">index</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/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;jcrSessionFactory&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springmodules.jcr.JcrSessionFactory&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;repository&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;repositoryCFB&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;credentials&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;jcrCredentials&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;sessionHolderProviderManager&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>
  <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;providers&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;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springmodules.jcr.jackrabbit.support.JackRabbitSessionHolderProvider&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;/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>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;seam:component</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Como las sesiones las va a manejar spring, es muy recomendable el uso de la plantilla JCR que nos proporciona el módulo de spring y así delegar en ella el control de las sesiones de  nuestro repositorio y evitar posibles problemas a la hora de sincronizarlas.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;jcrTemplate&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springmodules.jcr.JcrTemplate&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;jcrSessionFactory&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;allowCreate&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Ya tenemos configurados los orígenes de datos, y ahora ¿cómo gestionamos ambas transacciones? Spring nos permite configurar manejadores de transacciones de manera trasparente a las fuentes de datos y será el encargado de englobarlas en un mismo entorno. Este entorno transaccional será el que nos aporta nuestro servidor de aplicaciones (para el cual hemos definido las fuentes de datos correspondientes), lo obtendremos creando el siguiente bean dentro del contexto de spring:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;jtaTransactionManager&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.transaction.jta.JtaTransactionManager&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;transactionManagerName&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>java:/TransactionManager<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>La configuración del aspecto que nos manejará las transacciones que ocurran en nuestra aplicación será:</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;tx:advice</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;txAdvice&quot;</span> <span style="color: #000066;">transaction-manager</span>=<span style="color: #ff0000;">&quot;jtaTransactionManager&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tx:attributes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tx:method</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tx:method</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;get*&quot;</span> <span style="color: #000066;">read-only</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tx:attributes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tx:advice<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>El último paso es definir qué clases/métodos queremos que sean transaccionales mediante el uso de puntos de ruptura:</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;aop:config</span> <span style="color: #000066;">proxy-target-class</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;aop:pointcut</span> <span style="color: #000066;">expression</span>=<span style="color: #ff0000;">&quot;execution(* com.s2grupo.sample..*(..))&quot;</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;txServicePointCut&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:advisor</span> <span style="color: #000066;">advice-ref</span>=<span style="color: #ff0000;">&quot;txAdvice&quot;</span> <span style="color: #000066;">pointcut-ref</span>=<span style="color: #ff0000;">&quot;txServicePointCut&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:config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Para que los puntos de ruptura sean efectivos es necesario agregar las clases afectadas al contexto de spring. Como estas clases son utilizadas dentro del contexto de seam añadiremos el nodo <strong>&lt;seam:component/&gt;</strong> dentro de cada una de ellas. La configuración quedará:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">&lt;!-- Service --&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;repositoryService&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;repositoryManager&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;repositoryManager&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;seam:component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;repositoryService&quot;</span> <span style="color: #000066;">intercept</span>=<span style="color: #ff0000;">&quot;false&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;repositoryManager&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.s2grupo.sample.RepositoryManager&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">init-method</span>=<span style="color: #ff0000;">&quot;create&quot;</span> <span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;close&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;repositoryConfiguration&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;repositoryConfiguration&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;jcrTemplate&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;jcrTemplate&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;seam:component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;repositoryManager&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;repositoryConfiguration&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.s2grupo.sample.RepositoryConfiguration&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">init-method</span>=<span style="color: #ff0000;">&quot;create&quot;</span> <span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;close&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;jcrTemplate&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;jcrTemplate&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;seam:component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;repositoryConfiguration&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;myService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.s2grupo.sample.MyService&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;myDao&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;myDao&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;seam:component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;myService&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;!-- Data --&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;abstractDao&quot;</span> <span style="color: #000066;">abstract</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;hibernateSessionFactory&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;hibernateSession&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><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;myDao&quot;</span> <span style="color: #000066;">parent</span>=<span style="color: #ff0000;">&quot;abstractDao&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;seam:component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;myDao&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Y con esto tendríamos todas las transacciones controladas y no perderíamos así la integridad de los datos de nuestra aplicación.</p>
<p>Espero que esta entrada os sea tan útil como lo fue para mí. Y ahora ... comentarios!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.springartwork.es/2009/11/spring-jboss-seam-%c2%bfamor-imposible/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Introduccion al patron MVVM</title>
		<link>http://www.springartwork.es/2009/10/introduccion-al-patron-mvvm/</link>
		<comments>http://www.springartwork.es/2009/10/introduccion-al-patron-mvvm/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 09:37:31 +0000</pubDate>
		<dc:creator>Nedim Sabic</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://springartwork.s2grupo.es/?p=106</guid>
		<description><![CDATA[Con la llegada del Visual Studio 2008 y el cada vez más popular framework WPF (Windows Presentation Foundation), el uso del patrón MVVM para el desarrollo de aplicaciones se ha hecho prácticamente indispensable. Actualmente ya existen varios frameworks MVVM, algunos de ellos son de código libre, como por ejemplo Cinch.
La máxima del patrón MVVM es [...]]]></description>
			<content:encoded><![CDATA[<p>Con la llegada del Visual Studio 2008 y el cada vez más popular framework WPF (<a href="http://windowsclient.net/">Windows Presentation Foundation</a>), el uso del patrón MVVM para el desarrollo de aplicaciones se ha hecho prácticamente indispensable. Actualmente ya existen varios frameworks MVVM, algunos de ellos son de código libre, como por ejemplo <a href="http://cinch.codeplex.com/">Cinch</a>.</p>
<p>La máxima del patrón MVVM es la separación de las capas de presentación y negocio. Esto se consigue con el nuevo lenguaje declarativo llamado <a href="http://es.wikipedia.org/wiki/XAML">XAML</a> que permite establecer el <em>binding</em> entre los elementos visuales y los elementos del dominio, en nuestro caso las propiedades de las clases. Así, imaginemos que queremos enlazar un atributo de la clase que represente el nombre del empleado con la caja de texto que al iniciar la aplicación se muestre el nombre. En Windows Forms deberíamos crear el manejador de evento de carga del formulario, declarar la instancia de nuestra clase Empleado, e inicializar el valor de la propiedad Text de la caja de texto. Sin embargo en WPF, basta con escribir una instrucción en XAML que enlace nuestra caja de texto con el atributo. Lo mejor de todo es que al modificar el valor del texto, también se actualizará el valor del atributo que representa el nombre del empleado, y al revés.</p>
<p>Las siglas <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> vienen de <em><a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">Model-View-ViewModel</a></em>, donde como su propio nombre indica, Model representa el dominio de nuestro sistema, View los elementos que componen la interfaz y ViewModel se encargará de comunicar las vistas con el modelo.</p>
<p>La vista nunca interactuará directamente con el modelo, sino a través de los ViewModels.</p>
<p>Los desarrolladores familiarizados con ASP.NET pueden establecer un símil con WPF. Las páginas en ASP.NET disponen del código HTML y del <em>code behind</em> escrito en C# o Visual Basic. De manera similar, en WPF tenemos los archivos .xaml, y detrás de cada vista código en nuestro lenguaje de programación favorito como VB o C#. Con MVVM conseguiremos que la cantidad de código en code behind sea la mínima posible.</p>
<p>Después de esta breve introducción teórica veamos como llevar a cabo la implementación básica  del patrón MVVM en nuestra aplicación. Debido que muchos de los ViewModels necesitan la misma información, empezaremos creando la clase base ViewModelBase que heredarán nuestros ViewModels. Para organizarnos mejor, es buena práctica crear dentro de nuestro proyecto tres carpetas:</p>
<ul>
<li>ViewModels donde iremos alojando nuestro ViewModels</li>
<li>Models para almacenar nuestros modelos</li>
<li>Views para las vistas</li>
</ul>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> ViewModelBase <span style="color: #008000;">:</span> INotifyPropertyChanged <span style="color: #000000;">&#123;</span>
<span style="color: #008080; font-style: italic;">///</span>
<span style="color: #008080; font-style: italic;">/// Evento que se ejecuta cuando se cambia la propiedad del componente.</span>
<span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">event</span> PropertyChangedEventHandler PropertyChanged<span style="color: #008000;">;</span>
 <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> NotifyPropertyChanged<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span> sData<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>PropertyChanged <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   PropertyChanged<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span>, <span style="color: #008000;">new</span>   PropertyChangedEventArgs<span style="color: #000000;">&#40;</span>sData<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
 <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Como vemos debe implementar la interfaz <strong>INotifyPropertyChanged</strong>, concretamente el miembro <strong>NotifyPropertyChanged</strong>, que notificará al sistema de <em>binding</em> de WPF cuando la propiedad en el ViewModel disponga de nuevo valor, para actualizar en consecuencia todos los controles enlazados.</p>
<p>Para que WPF se de cuenta de que propiedad ha cambiado, al disparar el evento <strong>PropertyChanged</strong>, hemos de pasarle en el constructor de la clase <strong>PropertyChangedEventArgs</strong> el nombre completo de la propiedad.</p>
<p>A partir de ahora podemos empezar a definir nuestros ViewModels. Para el caso de estudio vamos a definir uno trivial que invoque los métodos del modelo añadiendo la cadena que se le pasa a la lista, eliminándola o obteniendo todas las cadenas disponibles.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ExampleViewModel <span style="color: #008000;">:</span> ViewModelBase
<span style="color: #000000;">&#123;</span>
 <span style="color: #0600FF;">private</span> ExampleModel exampleModel <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleModel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #0600FF;">private</span> ObservableCollection lDummyStrings <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ObservableCollection <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
 <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> doDummyAdd<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span> sDummy<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  exampleModel.<span style="color: #0000FF;">addDummy</span><span style="color: #000000;">&#40;</span>sDummy<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
&nbsp;
 <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> doDummyDel<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span> sDummy<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  exampleModel.<span style="color: #0000FF;">delDummy</span><span style="color: #000000;">&#40;</span>sDummy<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
&nbsp;
 <span style="color: #0600FF;">private</span> ObservableCollection getDummies<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">return</span> exampleModel.<span style="color: #0000FF;">getDummies</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>En una aplicación del mundo real el modelo se compondría de operaciones mucho más complejas, como el acceso a bases de datos. Anteriormente habíamos mencionado que el objetivo del MVVM es desacoplar el código correspondiente a la vista, pero si queremos saber cuándo el usuario aprieta un determinado botón o elige una valor de la lista, deberíamos instalar manejadores de eventos fuertemente acoplados a la vista. Por suerte, WPF incorpora un sistema de comandos mediante los cuales podemos llevar la lógica correspondiente de los manejadores de eventos a los ViewModels.</p>
<p>En primer lugar implementamos el patrón del comando genérico. Como vemos contiene dos delegados que podemos interpretar como, si la condición (el delegado <strong>CanExecuteDelegate</strong>) del comando se cumple entonces podemos  ejecutamos la acción (<strong>ExecuteDelegate</strong>).</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">///</span>
<span style="color: #008080; font-style: italic;">/// El comando génerico para ejecutar los métodos</span>
<span style="color: #008080; font-style: italic;">/// de la interfaz ICommand.</span>
<span style="color: #008080; font-style: italic;">///</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> GenericCommand <span style="color: #008000;">:</span> ICommand
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">public</span> Predicate 
&nbsp;
<span style="color: #0600FF;">public</span> Action
&nbsp;
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #008080; font-style: italic;">/// Indica si el comando se puede ejecutar.</span>
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> CanExecute<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">Object</span> param<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>CanExecuteDelegate <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
   <span style="color: #0600FF;">return</span> CanExecuteDelegate<span style="color: #000000;">&#40;</span>param<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
&nbsp;
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #008080; font-style: italic;">/// Se dispara cuando cambia la condición de ejecución del</span>
 <span style="color: #008080; font-style: italic;">///	comando.</span>
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">event</span> EventHandler CanExecuteChanged
 <span style="color: #000000;">&#123;</span>
  add <span style="color: #000000;">&#123;</span>
   CommandManager.<span style="color: #0000FF;">RequerySuggested</span> <span style="color: #008000;">+=</span> value<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
  remove<span style="color: #000000;">&#123;</span>
   CommandManager.<span style="color: #0000FF;">RequerySuggested</span> <span style="color: #008000;">-=</span> value<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
 <span style="color: #000000;">&#125;</span>
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #008080; font-style: italic;">/// Ejecutará el método del comando.</span>
 <span style="color: #008080; font-style: italic;">///</span>
 <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">Object</span> param<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>ExecuteDelegate <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
   ExecuteDelegate<span style="color: #000000;">&#40;</span>param<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Declaramos el comando que nos permitirá insertar la cadena que se le pase como parámetro en la colección:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> ICommand addDummyStringCommand<span style="color: #008000;">;</span></pre></div></div>

<p>Inicializamos los delegados del comando. Para ello vamos a usar una nueva estructura de .NET 3.0 denominada expresiones <em>lambda</em>, que de manera mucho más limpia nos permiten hacer lo que en la versión anterior del framework se hacía mediante delegados anónimos:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> doInitCommand<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
 <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">addDummyStringCommand</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GenericCommand<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
  CanExecuteDelegate <span style="color: #008000;">=</span> c <span style="color: #008000;">=&gt;</span> c <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span>,
  ExecuteDelegate <span style="color: #008000;">=</span> c <span style="color: #008000;">=&gt;</span> doDummyAdd<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span><span style="color: #000000;">&#41;</span> c <span style="color: #000000;">&#41;</span><span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">public</span> ICommand AddDummyStringCommand<span style="color: #000000;">&#123;</span>
 get <span style="color: #000000;">&#123;</span><span style="color: #0600FF;">return</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">addDummyStringCommand</span><span style="color: #008000;">;</span><span style="color: #000000;">&#125;</span>
 set<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">addDummyStringCommand</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
  NotifyPropertyChanged<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;AddDummyStringCommand&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Solamente cuando el parámetro sea distinto de null se podrá ejecutar el comando, es decir, el botón se habilitará.</p>
<p>Ahora veamos como enlazar nuestro comando con la vista desde el código XAML. Debemos inicializar la propiedad <strong>DataContext</strong> del elemento que participa en el <em>data binding</em>, en este caso la vista. Para ello en el constructor de la misma hacemos lo siguiente:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">partial</span> <span style="color: #FF0000;">class</span> ExampleView
<span style="color: #000000;">&#123;</span>
 <span style="color: #0600FF;">private</span> ExampleViewModel exampleViewModel <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleViewModel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
 <span style="color: #0600FF;">public</span> ExampleView<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
  InitializeComponent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">DataContext</span> <span style="color: #008000;">=</span> exampleViewModel<span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Con esto hemos establecido la conexión entre la UI de la aplicación y nuestro ViewModel. Ahora seremos capaces desde el código XAML de referenciar las propiedades de nuestro ViewModel.</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;Button</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;cmdAddDummyString&quot;</span> <span style="color: #000066;">Command</span>=<span style="color: #ff0000;">&quot;{Binding Path=AddDummyStringCommand}&quot;</span> <span style="color: #000066;">CommandParameter</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=txtDummyString, Path=Text}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/Button<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Aquí la propiedad <strong>Command</strong> del botón la hemos enlazado con el comando de nuestro ViewModel y el parámetro será la cadena que se escribirá en la caja de texto. Todo queda limpio, sin necesidad de invocar las operaciones de la lógica de negocio desde los manejadores de eventos. Además, de esta forma estamos reutilizando el código; si quisiéramos incorporar a nuestra aplicación la misma funcionalidad pero desde, por ejemplo, el menú, simplemente asignaríamos el mismo comando al ítem del menú</p>
<p>Imaginad ahora que queremos listar todas la cadenas que se vayan añadiendo o eliminando de la colección, en un Listbox. Si volvemos a la definición de nuestro ViewModel, el atributo <strong>lDummyStrings</strong> de tipo <strong>ObservableCollection</strong> se comporta como una lista normal, excepto que podemos ser notificados cuando se eliminan o añaden elementos a la misma. Suponiendo que en el ViewModel hemos definido la propiedad para devolver la lista, veamos como enlazarla con el Listbox:</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;ListBox</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding Path=BindableDummyStringCollection}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/Button<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Lo que en Windows Forms resultaría un proceso engorroso, en WPF mediante un par de líneas en XAML hemos enlazado el Listbox con la colección, y además a medida que se va modificando la colección el Listbox se actualiza automáticamente.</p>
<p>Hemos aprendido como llevar a cabo la implantación minimalista del patrón MVVM en nuestra aplicación mediante un ejemplo trivial, pero que sirve como el guía para desarrollar aplicaciones complejas. Actualmente, frameworks como <a href="http://cinch.codeplex.com/">Cinch</a> o <a href="http://proactive.inria.fr/release-doc/pa/multiple_html/Calcium.html">Calcium</a> ofrecen muchas características que nos pueden ayudar a la hora de implementar el MVVM.</p>
<p>Sin duda alguna, se está convirtiendo en de facto para el desarrollo de aplicaciones WPF.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.springartwork.es/2009/10/introduccion-al-patron-mvvm/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>If(&#8221;spring&#8221;==&#8221;primavera&#8221;){?¿?¿?¿}</title>
		<link>http://www.springartwork.es/2009/10/ifspringprimavera/</link>
		<comments>http://www.springartwork.es/2009/10/ifspringprimavera/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 10:26:23 +0000</pubDate>
		<dc:creator>Néstor Tarin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[spring-core]]></category>

		<guid isPermaLink="false">http://springartwork.s2grupo.es/?p=74</guid>
		<description><![CDATA[Si no estabais seguros de la temática de este blog, algunos me llamareis ¡loco!, otros os estaréis preguntando qué es eso de Spring y porqué es tan famoso, otros pensaréis que ya está otro pesao vendiéndonos el framework este. De cualquier modo, lo que busco en esta entrada es introducir este framework y emplear el [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.springartwork.es/wp-content/uploads/2009/10/hoja.jpg" style="float:left;padding:0px;margin:0px 20px 10px 0;border:0px solid #444;" />Si no estabais seguros de la temática de este blog, algunos me llamareis ¡loco!, otros os estaréis preguntando <strong>qué es eso de Spring</strong> y porqué es tan famoso, otros pensaréis que <strong>ya está otro <em>pesao</em> vendiéndonos el <em>framework</em> este</strong>. De cualquier modo, lo que busco en esta entrada es introducir este framework y emplear el blog en dar a conocer mi experiencia personal en el uso del <strong>Core de Spring</strong>. Como algunos de vosotros ya conoceréis, Spring posee multitud de aplicaciones y puesto que no puedo explicarlas todas en una entrada, para eso está este blog. Tiempo al tiempo...</p>
<p>La primera versión de Spring fue escrita por Rod Jonhson, quien lo lanzó primero con la publicación de su libro "Expert One-on-One Java EE Design and Development", basado en las mejores prácticas aceptadas. Tras la publicación, sus lectores le solicitaron que el código que acompañaba al libro fuera liberado bajo una licencia <em>Open Source</em>. A raíz de eso, se formó un pequeño equipo de desarrolladores que esperaba trabajar en extender el framework, y se creó el primer proyecto en <a href="http://sourceforge.net">Sourceforge</a> en febrero de 2003. Después de trabajar en su desarrollo durante más de un año, la primera versión (1.0) fue lanzada en marzo de 2004, momento a partir del cual Spring ganó mucha popularidad en la comunidad Java, debido en parte al uso de Javadoc y de una documentación de referencia por encima del promedio de un proyecto de código abierto. </p>
<p>Spring Framework hizo que aquellas técnicas que resultaban desconocidas para la mayoría de programadores se volvieran populares en un periodo muy corto de tiempo, cuyo ejemplo más notable fue la inversión de control. En el año 2004, Spring disfrutó de unas altísimas tasas de adopción y al ofrecer su propio framework de programación orientada a aspectos (<em>aspect-oriented programming</em>, AOP) consiguió hacer más popular su paradigma de programación en la comunidad Java. Actualmente <a href="http://www.springsource.org">springsource</a> ha sido adquirido por el líder en soluciones de virtualización VMWare (<a href="http://www.springsource.com/newsevents/vmware-acquire-springsource?__utma=1.3350880485029875700.1245053827.1252598455.1253517987.23&amp;__utmb=1.3.10.1253638374&amp;__utmc=1&amp;__utmx=-&amp;__utmz=1.1253517987.23.39.utmcsr=springsource.org|utmccn=(referral)|utmcmd=referral|utmcct=/projects&amp;__utmv=-&amp;__utmk=205092752" target="_blank">+ info</a>)</p>
<p>El principal objetivo del framework es <strong>FACILITAR EL DESARROLLO DE SOFTWARE (TANTO JAVA COMO .NET)</strong>. A lo largo de todas las liberaciones del proyecto, se han ido añadiendo módulos: Mensajería (JMS), Integración (ESB), Acceso a Datos (JDBC, ADO .Net, Hibernate), todos ellos con el propósito de reducir complejidad al desarrollo, permitiendo así que los desarrolladores dediquen sus esfuerzos a lo que realmente es necesario y “no reinventen la rueda”.</p>
<p>Actualmente la versión (java) estable del framework es la 2.5.6 y contiene los siguientes módulos:</p>
<p><img class="aligncenter size-medium wp-image-80" title="spring-overview" src="http://springartwork.s2grupo.es/wp-content/uploads/2009/09/spring-overview-300x236.png" alt="spring-overview" width="300" height="236" style="border:0;"/></p>
<p>Como primera aproximación al mundo de spring, explicaremos el corazón de Spring: <strong>La inversión de control (IoC)</strong>. <a href="http://es.wikipedia.org/wiki/Inversión_de_Control ">Según Wikipedia, la Definición de IoC</a> es la siguiente:</p>
<div style="margin: 0px 25px 15px 25px; padding:20px 25px 20px 25px; background-color:#eeeeee; border:1px solid #aaa;"><em>
<p>La inversión de control es un método de programación en el que el flujo de ejecución de un programa se invierte respecto a los métodos de programación tradicionales, en los que la interacción se expresa de forma imperativa haciendo llamadas a procedimientos o funciones. Tradicionalmente el programador especifica la secuencia de decisiones y procedimientos que pueden darse durante el ciclo de vida de un programa mediante llamadas a funciones. En su lugar, en la inversión de control se especifican respuestas deseadas a sucesos o solicitudes de datos concretas, dejando que algún tipo de entidad o arquitectura externa lleve a cabo las acciones de control que se requieran en el orden necesario y para el conjunto de sucesos que tengan que ocurrir. En los comienzos de la programación, los programas eran lineales y monolíticos. El flujo de ejecución era simple y predecible, ejecutándose línea tras línea. Aparecieron dos conceptos que revolucionaron la programación: la modularidad y la reutilización de los componentes: se crean bibliotecas de componentes reutilizables. El flujo se complica, saltando de componente a componente, y aparece un nuevo problema: la dependencia (acoplamiento) entre nuestros componentes.<br />
El problema se empieza a considerar lo suficientemente importante como para definir nuevos conceptos en el diseño:</p>
<ul>
<li><em>Inversión de Control (IoC)</em></li>
<li><em>Inyección de Dependencias (Dependency Injection, DI)</em></li>
</ul>
<p>El flujo habitual se da cuando es el código del usuario quien invoca a un procedimiento de una biblioteca, la inversión de control sucede cuando es la biblioteca la que invoca el código del usuario. Típicamente sucede cuando la biblioteca es la que implementa las estructuras de alto nivel y es el código del usuario el que implementa las tareas de bajo nivel.</p>
<p>La utilización de interfaces y la aparición de los frameworks ha popularizado este término. De hecho es el concepto central del Framework de Spring, ya que implementa un "Contenedor" que se encarga de gestionar las instancias (así como sus creaciones y destrucciones) de los objetos del usuario. Por tanto las aplicaciones que utilicen el framework de Spring (no Spring propiamente dicho) utilizarán Inversión de Control.</em></div>
<p>Creo que tras esta definición toca un ejemplito que sirva para aclarar algunas dudas (que seguramente no son pocas):</p>
<p>Sean dos clases cada una con su interfaz independiente: classA, classB, interfaceA e interfaceB. En classB tenemos un campo del tipo classA. Desde la clase principal, mainClass, se accede al campo del tipo classA de la clase classB.</p>
<p>Utilizando el método de programación habitual tendríamos lo siguiente:</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> ClassA <span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> <span style="color: #000000; font-weight: bold;">do</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Hello World&quot;</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;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ClassB <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> ClassA a<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> ClassB<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;">this</span>.<span style="color: #006633;">a</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassA<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>La clase principal seria:</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>
   <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> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      ClassB b <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassB<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>b.<span style="color: #006633;">a</span>.<span style="color: #000000; font-weight: bold;">do</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></pre></div></div>

<p>En la salida estándar obtenemos:</p>
<div style="margin: 0px 25px 10px 25px; padding:10px 25px 0px 25px; background-color:#eeeeee; border:1px solid #aaa;">
<p>$ Hello World</p>
</div>
<p>Analicemos el código del ejemplo. ¿Qué pasaría si las clases ClassA y ClassB pertenecieran a dos componentes totalmente distintos (p.ej. un conector JDBC y un cliente de servicios web)? ¿No estaríamos acoplando ambos componentes y haciendo que fueran totalmente dependientes uno del otro? ¿Que pasaría si decidiéramos cambiar un componente por otro distinto que en esencia tuviera la misma funcionalidad? ¿Tendríamos que cambiar ambos componentes? ¿Genera esto un código testeable unitariamente? Es decir, ¿podemos testear la clase ClassB sin testear la ClassA?</p>
<p>La respuesta a todas estas preguntas nos las puede dar el siguiente ejemplo:</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> InterfaceA<span style="color: #009900;">&#123;</span><span style="color: #003399;">String</span> <span style="color: #000000; font-weight: bold;">do</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> <span style="color: #000000; font-weight: bold;">interface</span> InterfaceB<span style="color: #009900;">&#123;</span> InterfaceA getA<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> <span style="color: #000000; font-weight: bold;">class</span> ClassA <span style="color: #000000; font-weight: bold;">implements</span> InterfaceA<span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> <span style="color: #000000; font-weight: bold;">do</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Hello World&quot;</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;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ClassB <span style="color: #000000; font-weight: bold;">implements</span> InterfaceB<span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">private</span> InterfaceA a<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setA<span style="color: #009900;">&#40;</span>InterfaceA a<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;">a</span> <span style="color: #339933;">=</span> a<span style="color: #339933;">;</span><span style="color: #009900;">&#125;</span>
   <span style="color: #000000; font-weight: bold;">public</span> InterfaceA getA<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">a</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>La clase principal seria:</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>
   <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> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      ClassB b <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      ClassA a <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassA<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      b.<span style="color: #006633;">a</span> <span style="color: #339933;">=</span> a<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>b.<span style="color: #006633;">a</span>.<span style="color: #000000; font-weight: bold;">do</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></pre></div></div>

<p>En este ejemplo no se están acoplando las clases ClassA y ClassB, con lo que conseguimos resolver todas las preguntas del ejemplo anterior. Hemos evitado el acoplamiento, ¿pero es cómodo? Si ahora necesito instanciar todas las clases y establecer sus campos, estoy mejorando la calidad de mi software, pero a un coste alto. Aquí es donde entra Spring:</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> InterfaceA<span style="color: #009900;">&#123;</span><span style="color: #003399;">String</span> <span style="color: #000000; font-weight: bold;">do</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> <span style="color: #000000; font-weight: bold;">interface</span> InterfaceB<span style="color: #009900;">&#123;</span> InterfaceA getA<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> <span style="color: #000000; font-weight: bold;">class</span> ClassA <span style="color: #000000; font-weight: bold;">implements</span> InterfaceA<span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> <span style="color: #000000; font-weight: bold;">do</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Hello World&quot;</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;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ClassB <span style="color: #000000; font-weight: bold;">implements</span> InterfaceB<span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">private</span> InterfaceA a<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setA<span style="color: #009900;">&#40;</span>InterfaceA a<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;">a</span> <span style="color: #339933;">=</span> a<span style="color: #339933;">;</span><span style="color: #009900;">&#125;</span>
   <span style="color: #000000; font-weight: bold;">public</span> InterfaceA getA<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">a</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Archivo de definición de beans (applicationContext.xml):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?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;</span>
<span style="color: #009900;">         http://www.springframework.org/schema/beans</span>
<span style="color: #009900;">         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&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 style="color: #000000; font-weight: bold;">&gt;</span></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;classA&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;classB&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;a&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;classA&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>
<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>La clase principal seria:</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>
   <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> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      ClassPathXmlApplicationContext 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: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> <span style="color: #0000ff;">&quot;applicationContext.xml&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      InterfaceB b <span style="color: #339933;">=</span> ctx.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;classB&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>b.<span style="color: #006633;">getA</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #000000; font-weight: bold;">do</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></pre></div></div>

<p>La implementación anterior sería la más correcta posible: desde el método main se carga el contexto de Spring, que se encarga de instanciar todas las clases y de realizar la inyección de dependencias. Tras esta inicialización, obtenemos el "bean" desde el contexto a través del nombre, con lo que hemos diseñado una aplicación totalmente desacoplada y de una manera muy sencilla.</p>
<p>Sirva esto de rápida introducción a Spring. Y si no se han aclarado, utilicen los comentarios o sean pacientes; en poco tiempo le cogerán el gusto a este <em>framework</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.springartwork.es/2009/10/ifspringprimavera/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
