<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.1" -->
<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/"
	>

<channel>
	<title>MemeStorm</title>
	<link>http://www.memestorm.com/blog</link>
	<description>Exploring the Spring Framework and Application Development</description>
	<pubDate>Thu, 22 Nov 2007 19:49:28 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.1</generator>
	<language>en</language>
			<item>
		<title>Testing Java Persistence API (JPA) Entities Outside the Container</title>
		<link>http://www.memestorm.com/blog/testing-java-persistence-api-jpa-entities-outside-the-container/</link>
		<comments>http://www.memestorm.com/blog/testing-java-persistence-api-jpa-entities-outside-the-container/#comments</comments>
		<pubDate>Mon, 06 Nov 2006 22:22:53 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/testing-java-persistence-api-jpa-entities-outside-the-container/</guid>
		<description><![CDATA[Testing Java Persistence API (JPA) Entities Outside the Container]]></description>
			<content:encoded><![CDATA[<p>When I wrote about the <a href="http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/">Java Persistence API (JPA), Spring and Eclipse Web Tools Platform (WTP)</a> I neglected to show how easy it was to <em>test</em> our JPA entities.</p>
<p>Traditionally, testing EJBs outside of a container was an absolute pain.  Testing JPA is embarrassingly easy, especially with Spring doing all the heavy lifting.  You’ll have no excuse to write your integration tests now..</p>
<h3>Our goal</h3>
<p>Our goal here is to test or DAO class, <code>MyDAO</code>, shown <a href="http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/">here</a>.  This can be used as the basis of larger integration tests for example.  Here are some of the issues in setting up a test, which we’ll neatly sidestep later:</p>
<ul>
<li>We need to set up the entity manager, hopefully just once as this is time consuming.</li>
<li>We need to handle the automatic dependency injection.  Remember that this DAO can run on a server, where it expects the entity manager to be automatically injected.</li>
<li>We need some kind of transaction management.  Ideally we don’t want to start and commit transactions in every test method.  DRY!</li>
<li>A popular way of testing code that interacts with databases these days is to start each test with a transaction, and then after running the test, roll back the transaction so that any database changes aren’t actually committed.  This leaves your database in an orderly state.</li>
<li>Ideally we’d like access to JDBC too - just to check our JPA stuff is doing its thang.</li>
<li>We may need to handle class instrumentation when using JPA</li>
</ul>
<h3>How to do it</h3>
<p>Well, I’m going to show you some code that does all of the above.  You’ll be shocked at how little I have to do:</p>
<pre><code>import org.springframework.test.jpa.AbstractJpaTests;

public class MyDAOTests extends AbstractJpaTests {
    MyDAO myDAO;
    @Override
    protected String[] getConfigLocations() {
        return new String[] {
                "/com/memestorm/service/jpa/applicationContext.xml",
                "/com/memestorm/service/jpa/applicationContext-jpa.xml"
        };
    }

    public void testInsertUser() {
            Collection users = getMemeService().getUsers();
            int found = users.size();
            User u = new User("test", "test");
            getMemeService().addUser(u);
            users = getMemeService().getUsers();
            assertEquals(found + 1, users.size());
    }

    // More tests... then

    public MyDAO getMemeService() {
            return myDAO;
    }
}
</code></pre>
<p>I’m sorry, did you blink?  Go read that again.  Isn’t that neat?  Let’s look at what’s happening:</p>
<ul>
<li>Obviously the <code>getConfigLocations()</code> method points to our application context configuration files (I’m using the same ones as in the previous blog entry).  Spring uses this to establish the entity manager, database connections etc.  It does this once, and all the tests methods use the results.</li>
<li>Spring automatically injected the dependencies.  Did you see that <code>myDAO</code> variable and its setter?  Spring managed that itself.</li>
<li>Spring automatically starts a transaction for every test method and rolls it back afterwards.</li>
<li>Spring silently handles all class instrumentation.</li>
</ul>
<p>Now you have no excuses for writing your own tests.  You are positively coddled by <code>AbstractJpaTests</code>.</p>
<h3>Adding a few features</h3>
<p><code>AbstractJpaTests</code> provides a lot of additional functionality.</p>
<h4>JDBC</h4>
<p>Sometimes you want to incorporate some JDBC too.  Here’s a method that does so:</p>
<pre><code>public void testInsertUserSQL() {
    Collection users = getMemeService().getUsers();
    int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");
    assertEquals(users.size(), count);
}
</code></pre>
<p>Easy huh?  The <code>jdbcTemplate</code> is set up for you in one of the superclasses.</p>
<h4>Transactions</h4>
<p>You don’t have to wait until the method ends to end the transaction.  You can optionally call the method <code>endTransaction()</code> if you like.  By default, this will force the rollback of the transaction—remember that’s what typically happens automatically for  you at the end of each test method.<br />
If you want the transaction to actually <em>commit</em> for a particular test method, then call the <code>setComplete()</code> method.   This sets a flag, read in the <code>endTransaction()</code> method, to tell the test harness to commit instead of rollback.  More complex operations can be carried out too, for example you can end a transaction in a test method, and in the same method begin a new one by calling <code>startNewTransaction()</code>.  Check out Spring’s <code>AbstractTransactionalSpringContextTests</code> for all of this support.</p>
<h4>Entity Manager</h4>
<p>You can also get access to the entity manager.  Here’s an example that uses some of JPA’s <code>Query</code> interface:</p>
<pre><code>public void testNamedParameter() {
  User us = new User("test","last");
  getMemeService().storeUser(us);

  Query q = this.sharedEntityManager.createQuery(
         "select u from User u where u.firstName = :name");
  q.setParameter("name", "test");
  User u = (User) q.getSingleResult();
  assertEquals(u.getFirstName(), "test");
}
</code></pre>
<p>As you can see, the exposed <code>sharedEntityManager</code> is the entity manager attached to the current transaction.</p>
<h3>Caveats</h3>
<p>Say you have a <code>User</code> class that’s in a ManyToOne unidirectional relationship with a <code>Building</code> class, like this:</p>
<pre><code>@Entity
public class User {
    /* Unidirectional */
    @ManyToOne
    @JoinColumn(name="bldng_id")
    Building building;

    // ..
}
</code></pre>
<p>Imagine we write a test case, like this:</p>
<pre><code>public void testBuilding() {
    User u = new User("test","test");
    Building b = new Building();
    b.setName("BuildingA");
    u.setBuilding(b);
    getMemeService().addUser(u);
    **//getMemeService().addBuilding(b);**
}
</code></pre>
<p>Here we’ve made a  mistake and didn’t persist the building object (it’s required - it’s not cascaded after all).  What will happen when you run this test?</p>
<p>Well, the green flag will be raised high, unfortunately.  Say we changed the test like so:</p>
<pre><code>public void testBuilding() {
    User u = new User("test","test");
    Building b = new Building();
    b.setName("BuildingA");
    u.setBuilding(b);
    getMemeService().addUser(u);

    Collection usersAfter = getMemeService().getUsers();
}
</code></pre>
<p>If you run <em>this</em> test, you’ll get an exception</p>
<pre><code>java.lang.IllegalStateException: During synchronization
a new object was found through a relationship that was
not marked cascade PERSIST.
</code></pre>
<p>In other words, the <code>getUsers()</code> method, which simply does <code>em.createQuery("SELECT user from User user").getResultList()</code>, results in the persistence context realizing that there is indeed an object that should have been persisted.</p>
<p>My point is this: I’ve added the final test line there for no good reason, but it’s caught a bug in my persistence logic.  That’s a bit ugly - I wish there was some way in which I could force the O/R tool to do some kind of “spot consistency check” to help me out.   Hopefully if we have enough tests in our service layer going through to the DAO layer, it’ll catch these types of things.  Perhaps Andy over at the excellent <a href="http://thediscoblog.com/">Disco Blog</a> will be kind enough to point the way one day <img src='http://www.memestorm.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/testing-java-persistence-api-jpa-entities-outside-the-container/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Java Persistence API (JPA), Spring and Eclipse Web Tools Platform (WTP)</title>
		<link>http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/</link>
		<comments>http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/#comments</comments>
		<pubDate>Mon, 30 Oct 2006 14:52:23 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/</guid>
		<description><![CDATA[Java Persistence API (JPA), Spring and Eclipse Web Tools Platform (WTP)]]></description>
			<content:encoded><![CDATA[<p>It’s time to add some persistence to our talks.  I spent a good two hours trying to get Spring, JPA and Eclipse to play along.  Here’s what I eventually did…So our goal is to create a project that I can run from within Eclipse, or deploy to something like Tomcat or an application server.  It uses HSQLDB, though you can obviously change database, and Toplink Essentials (though you can obviously change JPA provider too).  I use Tomcat 5.5.20 here. Oh, and Spring 2.0.  All of the necessary software libraries (besides Tomcat) can be found bundled in the full Spring 2.0 distribution.  I don’t use all of Spring’s JPA utilities either - I tried to stick to generic JPA stuff.</p>
<h4>Our JPA Code</h4>
<p>The only tricky part is setting up the application context for JPA’s entity manager factory.  After that it’s plain sailing, writing nice JPA code.  Here’s an example of one of the beans in our model:</p>
<pre><code>@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    String firstName;
    String lastName;

    @OneToOne
    @JoinColumn(name="pwd_id")
    Password password;

    @ManyToOne
    @JoinColumn(name="bldng_id")
    Building building;

    @OneToOne(mappedBy="owner")
    Cup cup;

    // omitted getters and setters
}
</code></pre>
<p>It’s a POJO, appropriately annotated.  In this case we have some extra OneToOne (unidirectional), ManyToOne (unidirectional) and OneToOne(bidirectional) relationships, but feel free to omit them.  This is pure POJO and JPA - there is no Spring in here at all.</p>
<p>That’s the kind of code we want to write for our domain model, so what about our DAO code?  Here’s our full DAO:</p>
<pre><code>@Transactional
public class MyDAOImpl implements MyDAO {

    private EntityManager em;

    // Spring will inject this:
    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    public Collection getUsers() {
        return em.createQuery("SELECT user from User user").
             getResultList();
    }

    public User loadUser(int id) {
        return em.find(User.class, id);
    }

    public void addUser(User user) {
        em.persist(user);
    }

    public Cup getCup(int id) {
        return em.find(Cup.class, id);
    }

}
</code></pre>
<p>This is pretty straightforward.  The only Spring dependency we have here is the <code>@Transactional</code>, and that’s because I wanted Spring to make all the methods transactional and avoid writing blobs of repeated code.  Notice the standard <code>@PersistenceContext</code> annotation.  Spring will magically fill this in for us - it acts like a JPA container.</p>
<p>I like this code.  It’s all neat, with minimal dependencies.  Let’s look at how to wire it up to work with Spring.</p>
<h4>Spring’s Application Context</h4>
<p>I’ve created an <code>applicationContext-jpa.xml</code> configuration file for all the JPA stuff.  It’s all pretty obvious once explained, I think…Here are all the bits with commentary:</p>
<p>First we set up a nice little property configurer, so you can just modify <code>jdbc.properties</code> to change the database:</p>
<pre><code>&lt;bean id="propertyConfigurer" class="org.....PropertyPlaceholderConfigurer"&gt;
    &lt;property name="location" value="/WEB-INF/jdbc.properties"/&gt;
&lt;/bean&gt;
</code></pre>
<p>Now a simple datasource:</p>
<pre><code>&lt;bean id="dataSource"
   class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
    &lt;property name="driverClassName" value="${jdbc.driverClassName}"/&gt;
    &lt;property name="url" value="${jdbc.url}"/&gt;
    &lt;property name="username" value="${jdbc.username}"/&gt;
    &lt;property name="password" value="${jdbc.password}"/&gt;
&lt;/bean&gt;
</code></pre>
<p>Now for the meaty bit:</p>
<pre><code>&lt;bean id="entityManagerFactory"
   class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
    &lt;property name="persistenceUnitName" value="MySpring"/&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
    &lt;property name="loadTimeWeaver"&gt;
    &lt;bean
        class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/&gt;
    &lt;/property&gt;
    &lt;!--  I'm not sure this is really necessary.. --&gt;
    &lt;property name="jpaVendorAdapter"&gt;
        &lt;bean
          class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter"&gt;
            &lt;property name="databasePlatform"
             value="oracle.toplink.essentials.platform.database.HSQLPlatform"/&gt;
            &lt;property name="generateDdl" value="true"/&gt;
            &lt;property name="showSql" value="true" /&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
    &lt;/bean&gt;
</code></pre>
<p>Now the important bit is the type of Spring entity manager factory you choose, and the weaver.  Many JPA implementations (not all) require a runtime weaver of some kind.  I had real trouble getting things to work with the SimpleLoadTimeWeaver in Eclipse.  I suspect class loading errors were causing the problem. I ended up with the InstrumentationLoadTimeWeaver which requires that you start your Java VM with an additional argument:</p>
<pre><code>-javaagent:/Java/workspace2/spring/dist/weavers/spring-agent.jar
</code></pre>
<p>To do this in Eclipse, hit “Run”, then “Run…” - select your server (for example, “Tomcat 5.5 Server”), hit the “Arguments” tab and insert the above in the “VM Arguments” box.</p>
<p>Some of the other weavers require me to modify Tomcat (by adding a context.xml file for example) to make Tomcat use Spring’s weaver - but I could not figure out how to do this with WTP - WTP provides no way for me to set this.</p>
<p>Moving on:</p>
<pre><code>&lt;!-- A simple transaction manager for our (single) EntityManagerFactory.  --&gt;
&lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
    &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;
&lt;tx:annotation-driven/&gt;
</code></pre>
<p>Here we create a simple transaction manager, and tell Spring we want to use its declarative <code>@Transaction</code> management.</p>
<p>This makes Spring perform the magic <code>@PersistenceContext/@PersitenceUnit</code> injection:</p>
<pre><code>&lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/&gt;
</code></pre>
<p>Finally, we can declare our DAO:</p>
<pre><code>&lt;bean id="service" class="com.memestorm.service.jpa.MyDAOImpl" /&gt;
</code></pre>
<p>Note that we don’t specify the entity manager as a dependency.  The bean post processor above will sort that out for us.</p>
<p>That’s it, we’re done!  In the end, there wasn’t too much to it except for the wrangling with the various weavers and entity managers.  Ben Hale provides <a href="http://blog.interface21.com/main/2006/08/07/using-jpa-in-spring-without-referencing-spring/">a similar writeup</a> though I got the same <code>org.springframework.dao.InvalidDataAccessApiUsageException</code> exceptions as some of his readers.</p>
<h4>Download</h4>
<p>The full source for the application is here.  As usual, it assumes that you have the full Spring distribution unpacked in a sibling directory.  Run the libraries Ant task to transfer the dependencies, and the <code>server.sh</code> in the db directory to start the database.  I’ve run this within Eclipse (3.2.1) WTP (1.5.1) successfully, and deployed as a WAR to Tomcat 5.5.20.</p>
<p><a href="http://www.memestorm.com/blog/wp-content/uploads/2006/10/springjpa.zip">springjpa.zip</a></p>
<p><!-- Technorati Tags Start --></p>
<p>Technorati Tags:<br />
<a href="http://technorati.com/tag/spring+framework" rel="tag">Spring Framework</a>,<br />
<a href="http://technorati.com/tag/JPA" rel="tag">JPA</a></p>
<p><!-- Technorati Tags End --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/java-persistence-api-jpa-spring-and-eclipse-web-tools-platform-wtp/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Session-scoped Beans in Spring 2.0</title>
		<link>http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/</link>
		<comments>http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/#comments</comments>
		<pubDate>Tue, 10 Oct 2006 13:58:00 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/</guid>
		<description><![CDATA[Spring 2.0 introduces a new way of scoping beans. We've spoken about singleton scoped beans in the past and there are factory beans too. ]]></description>
			<content:encoded><![CDATA[<p>Spring 2.0 introduces a new way of scoping beans.  We&#8217;ve spoken about singleton scoped beans in the past and there are factory beans too.  Now there are <em>session</em>, <em>request</em> and other types of bean scopes.  As you might imagine, a Spring bean scoped to the sessions means that it lives as long as the session.  This means that if you ask Spring&#8217;s IoC container for a bean that is session-scoped, it will instantiate it once only for that particular user&#8217;s session—different users in different sessions will get their own bean instances.  It gets even cooler if you set this bean as a dependency for another bean that is a singleton. It still works, but in this case Spring injects a smart proxy to handle the dynamic bean swapping (the container bean will get a different dependent bean depending on the session). All of this magic is dead simple to implement and use.</p>
<h4>How to do it</h4>
<p>Let&#8217;s look at how to create a simple session-scoped bean that can be retrieved from the context.  If you are using a <code>DispatcherServlet</code> (which you will be if you are using <a href="http://www.memestorm.com/blog/basic-web-mvc-example-in-pictures/">Spring&#8217;s MVC</a>) then all you need to do is tag the bean as session-scoped in your application context configuration file.  For example:</p>
<pre>
  &lt;bean id="mybean" class="com.memestorm.ex.MyBean"
        <strong>scope=&#8221;session&#8221;</strong>/&gt;</pre>
<p>Not much to do&#8230;as you&#8217;ll see, the only difference is the <code>session</code> attribute.  If you aren&#8217;t using the <code>DispatcherServlet</code> then you&#8217;ll need to add a (small) bit of extra configuration to <code>web.xml</code>:</p>
<pre>
  &lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.request.RequestContextListener&lt;/listener-class&gt;
  &lt;/listener&gt;</pre>
<p>You need to do this because of the mechanics of how this is implemented, which we&#8217;ll look at later.  For now remember that if you&#8217;re already using Spring&#8217;s MVC, you don&#8217;t need to do anything.  The bean, <code>MyBean</code> is nothing special—here&#8217;s the one we use:</p>
<pre>
    public class MyBean {
    	public MyBean() {
    		System.err.println("In Constructor!!!");
    	}
    }</pre>
<p>So now that we&#8217;ve defined our bean in our context, how do we use it?  Well, just like you&#8217;d use any other bean really!  Here&#8217;s an example of a controller grabbing the bean from our application context:</p>
<pre>
 // retrieve context
 ApplicationContext ac = org.springframework.web.context.support.
   WebApplicationContextUtils.getRequiredWebApplicationContext(
                       request.getSession().getServletContext());
 // grab bean
 MyBean mb = (MyBean) ac.getBean("mybean");</pre>
<p>This is what you&#8217;d do anyway.  The key isn&#8217;t that you have change the way you program - but it&#8217;s the way Spring manages the creation of the bean.</p>
<h4>What happens?</h4>
<p>The bean (<code>MyBean</code>) won&#8217;t be created <em>only once</em> (a singleton) for all users—rather it will be created once for each user session.  The magic is that it&#8217;s effectively tied to the user&#8217;s session (and created lazily as a result).  Here&#8217;s a concrete use case used in the Spring documentation: User Preferences.  If your user is logged on and you retrieve a session-scoped bean for the first time, it will be created.  While the user is logged on (he has a session) that bean will remain effectively tied to the session so that if you access the bean again (from the context), it will simply retrieve it and not create it again.</p>
<p>You can test this with the supplied example.  The <code>index</code> handler just tells me if the session is new (if it is, and you access the bean, you should expect a new instance to be created).  The <code>access</code> handler actually tries to retrieve the bean from the context.  You&#8217;d expect this to create the bean if the session is new, or simply just retrieve it if it&#8217;s not.  The <code>invalidate</code> handler invalidates the session.  Download the example and play - check the console to see the constructor message and when it appears.</p>
<h4>More Advanced Work</h4>
<p>Let&#8217;s look at the situation with dependencies.  For example, imagine our session-scoped bean has a dependency on some singleton:</p>
<pre>
  &lt;bean id="myotherbean" class="com.memestorm.ex.MyOtherBean" /&gt;

  &lt;bean id="mybean" class="com.memestorm.ex.MyBean" scope="session"&gt;
    &lt;property name="mob" ref="myotherbean" /&gt;
  &lt;/bean&gt;</pre>
<p>What happens now?  Well, <code>myotherbean</code> will be created once with the context, and the same instance will be injected into each <code>mybean</code> instance that is created as each user creates a session.  Neat huh?  But I guess you&#8217;d expect that behaviour.</p>
<h4>Even More Advanced Work</h4>
<p>Let&#8217;s flip the injection described in the previous scenario.  Imagine you have a bean that has a session-scoped bean as a dependency:</p>
<pre>
  &lt;bean id="mybean" class="com.memestorm.ex.MyBean" scope="session"&gt;
	&lt;property name="mob" ref="myotherbean" /&gt;
 	 <strong>&lt;aop:scoped-proxy/&gt;</strong>
  &lt;/bean&gt;
  &lt;bean id=&#8221;yetanotherbean&#8221; class=&#8221;com.memestorm.ex.YetAnotherBean&#8221;&gt;
    <strong> &lt;property name=&#8221;mybean&#8221; ref=&#8221;mybean&#8221; /&gt;</strong>
  &lt;/bean&gt;</pre>
<p>You&#8217;ll notice I had to do one surprising thing—it&#8217;s that magic AOP proxy incantation.  Essentially the problem is this: if <code>mybean</code> is only created when accessed from a session, and multiple times for each different session, how do we know what to inject into <code>yetanotherbean</code> because <code>yetanotherbean</code> is a simple singleton created when the Spring context is created?</p>
<p>The answer is of course: it doesn&#8217;t and cannot know.  So what we have to do is stuff in a proxy that behaves like the object (in fact it goes and grabs the object from the user&#8217;s session when you access it).  Spring does all the heavy lifting for you in this case - all you need to do is add the <code>scoped-proxy</code> tag.  This is pretty neat magic.  I&#8217;ve included a download to a more advanced application that uses this approach too.  Note that to do this proxying Spring needs <code>cglib</code> in the classpath.</p>
<h4>Downloads</h4>
<ul>
<li>Simple: <a href="http://www.memestorm.com/blog/wp-content/uploads/2006/10/scopexample.zip">scopexample.zip</a></li>
<li>AOP dynamic dependency version: <a href="http://www.memestorm.com/blog/wp-content/uploads/2006/10/ascopexample.zip">ascopexample.zip</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Lazy bean instantiation in Spring 2.0</title>
		<link>http://www.memestorm.com/blog/lazy-bean-instantiation-in-spring-20/</link>
		<comments>http://www.memestorm.com/blog/lazy-bean-instantiation-in-spring-20/#comments</comments>
		<pubDate>Sun, 04 Jun 2006 14:06:35 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject><dc:subject>ioc</dc:subject><dc:subject>lazy</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/lazy-bean-instantiation-in-spring-20/</guid>
		<description><![CDATA[Spring 2.0 introduces a new way of instantiating beans defined in a
bean factory&#8212;<i>lazily</i>. Generally all singleton beans are
instantiated as one of the last things that a bean factory does.  You
can now change this behaviour slightly and ensure that a bean factory
doesn't instantiate your bean at all - until such time as it's
requested for example.]]></description>
			<content:encoded><![CDATA[<p>Spring 2.0 introduces a new way of instantiating beans defined in a<br />
bean factory—<em>lazily</em>. Generally all singleton beans are<br />
instantiated as one of the last things that a bean factory does.  You<br />
can now change this behaviour slightly and ensure that a bean factory<br />
doesn&#8217;t instantiate your bean at all - until such time as it&#8217;s<br />
requested for example.</p>
<h4>How to do it</h4>
<p>Simply use the new <code>lazy-init</code> attribute in your bean definition.  For example:</p>
<pre>
&lt;bean id="turtle" class="com.memestorm.FooT"
      <strong>lazy-init=&#8221;true&#8221;</strong> /&gt;
&lt;bean id=&#8221;fox&#8221; class=&#8221;com.memestorm.FooF&#8221;
      <strong>lazy-init=&#8221;false&#8221;</strong> /&gt;</pre>
<p>Here <code>turtle</code> is defined to instantiate lazily, while <code>fox</code> will do so eagerly. In fact, we don&#8217;t need the <code>lazy-init="false"</code> attribute on <code>fox</code> at all - by default things are not lazy.</p>
<h4>What happens?</h4>
<p>Well, if these beans were defined in your application context then the <code>fox</code> bean will be created as usual (eagerly, as a singleton), but the <code>turtle</code> won&#8217;t be.  That&#8217;s almost all there is to it.  Of course, if your Java code tries to grab the bean from the context it will be instantiated at that time:</p>
<pre>
 FooF = (FooF) context.getBean("fox");</pre>
<p>There is a caveat.  If <code>turtle</code> was defined as dependency of <code>fox</code>, then of course the context will ensure that <code>turtle</code> is created eagerly too.  It&#8217;s the only way to satisfy the constraint after all.  So for example, here both beans will be created eagerly even though one is marked as lazy:</p>
<pre>
&lt;bean id="not-quite-turtle" class="com.memestorm.FooT"
      <strong>lazy-init=&#8221;true&#8221;</strong> /&gt;
&lt;bean id=&#8221;fox&#8221; class=&#8221;com.memestorm.FooF&#8221;
      <strong>depends-on=&#8221;turtle&#8221;</strong> /&gt;</pre>
<h4>A possible use</h4>
<p>I found a possible use in the petclinic application distributed with Spring.  Here it is in a nutshell.  Say you have two beans, in this case implementing specialized functionality:</p>
<pre>
&lt;bean id="hsqlClinic" class="org.springframework.....HsqlJdbcClinic"
      lazy-init="true"&gt;
  &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;

&lt;bean id="mysqlClinic" class="org.springframework.....MySQLJdbcClinic"
      lazy-init="true"&gt;
  &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;</pre>
<p>Now say one of these classes will be used somewhere, say as the target of an transaction intercepter:</p>
<pre>
&lt;bean id="clinic" class="org....TransactionProxyFactoryBean"&gt;
  &lt;property name="transactionManager" ref="transactionManager"/&gt;
  &lt;property name="target" ref="${petclinic.jdbcImplBeanName}"/&gt;
&lt;/bean&gt;</pre>
<p>Now it should be clear to you.  If, in my properties file, I set <code>petclinic.jdbcImplBeanName=hsqlClinic</code>, then the <code>hsqlClinic</code> bean will be used.  Moreover, the <code>mysqlClinic</code> bean won&#8217;t even be instantiated.  This nicely externalizes the configuration.  To switch implementations, merely change the property to <code>mysqlClinic</code>.</p>
<h4>How does it work?</h4>
<p>You don&#8217;t have to know this, but here&#8217;s how the magic happens.  The essential difference is in the <code>preInstantiateSingletons()</code> method in <code>DefaultListableBeanFactory</code>.  This is the magic method that pre-instantiates all singletons defined in the bean factory.  All that&#8217;s changed here, is that it ignores the bean if the <code>lazy-init</code> is set to true:</p>
<pre>
for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) {
  String beanName = (String) it.next();
  if (!cacheContainsSingleton(beanName) &amp;&amp; containsBeanDefinition(beanName)) {
    RootBeanDefinition bd = getMergedBeanDefinition(beanName, false);
    if (!bd.isAbstract() &amp;&amp; bd.isSingleton() &amp;&amp; <strong>!bd.isLazyInit()</strong>) {
      &#8230;.do instantiation work and put result in cache&#8230;.
    }
  }
}</pre>
<a href="http://www.memestorm.com/blog/index.php?tag=ioc" rel="tag">ioc</a>  <a href="http://www.memestorm.com/blog/index.php?tag=lazy" rel="tag">lazy</a>]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/lazy-bean-instantiation-in-spring-20/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Basic Spring Web services with XFire and JSR 181</title>
		<link>http://www.memestorm.com/blog/basic-spring-web-services-with-xfire-and-jsr-181/</link>
		<comments>http://www.memestorm.com/blog/basic-spring-web-services-with-xfire-and-jsr-181/#comments</comments>
		<pubDate>Wed, 31 May 2006 02:13:49 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/basic-spring-web-services-with-xfire-and-jsr-181/</guid>
		<description><![CDATA[Here's a simple example of how to expose Spring POJOs as Web services using XFire and JSR 181]]></description>
			<content:encoded><![CDATA[<p>I hadn&#8217;t intended to expose any of our functionality with Web services so soon, but that&#8217;s the great thing about Spring—many of the services are orthogonal to each other.  Let&#8217;s look at how we can expose some Spring beans as Web services.  We&#8217;ll do it using JSR 181 too, which means that the Web service implementation is so easy that even a Ruby hacker could write it&#8230;;-)</p>
<h4>Web Services and JSR 181</h4>
<p>Look <a href="http://dev2dev.bea.com/pub/a/2004/10/Anil_WServices.html">here</a> for an introduction to JSR 181 and where it fits in to the world of Web services.  You need not though, as it&#8217;s pretty simple.  First, let&#8217;s define the interface to our simple Web service:</p>
<pre>
package com.memestorm.ws;

import javax.jws.WebService;

<strong>@WebService( targetNamespace = &#8220;http://memestorm.com/skeleton1/AuthorService&#8221; )</strong>
public interface AuthorService {

	public String sayHello();

}</pre>
<p>That&#8217;s it.  Note the nice <code>@WebService</code> annotation. It&#8217;s all that&#8217;s really necessary. I threw in the <code>targetNamespace</code> attribute to show how you can modify things.  The system will automatically generate a WSDL file - and using these attributes (and others) you can modify the generated WSDL.  Now that we have the interface, let&#8217;s implement it!</p>
<pre>
package com.memestorm.ws;

import javax.jws.WebService;

@WebService(
  serviceName = "MyAuthorService",
  endpointInterface = "com.memestorm.ws.AuthorService"
)
public class AuthorServiceImpl implements AuthorService {

  public String sayHello() {
    return "Hello World Services!";
  }
}</pre>
<p>Oh my, that was easy&#8230;.There&#8217;s nothing to say, except:</p>
<ul>
<li>Do you see how there aren&#8217;t any external dependencies in this code?  The only thing I import is the annotation&#8230;this is cool&#8230;</li>
<li>This is just a POJO - which we&#8217;ll be defining in a Spring context file.  So we can easy wire it up with other beans using IoC.</li>
<li>This is an example of <a href="http://www.memestorm.com/blog/convention-over-configuration-in-springs-mvc/">CoC</a> again—you don&#8217;t have to do much other than write <code>@WebService</code>.</li>
</ul>
<p>Okay, now that we&#8217;ve written our Web service - and you can write as many as you like of course, let&#8217;s look at how to wire it all together.</p>
<h4>Hooking XFire into your Spring Application</h4>
<p>I used <a href="http://xfire.codehaus.org/">XFire</a> as the Web services stack here.  It implements some nice things that I don&#8217;t find in Apache Axis, such as the JSR 181 stuff, multiple XML binding mechanisms, multiple transports (including Jabber &amp; JMS) etc.  You only have to hook it into your web application once.   After that, simply create your POJOs and expose them.  What you need to do is:</p>
<ol>
<li>Create the XFire Spring context configuration file.  It&#8217;s here that you expose your POJOs, and where you can wire in other Spring beans etc.</li>
<li>Modify the Web application <code>web.xml</code> to deploy the XFire  servlet</li>
<li>Modify your build process to include all the right JARs</li>
</ol>
<p>Let&#8217;s look at these in order.</p>
<p><strong>1. XFire Configuration File</strong></p>
<p>Now XFire&#8217;s pretty powerful.  You can configure just about anything, and much of this you can do from the configuration file.  It&#8217;s also where you expose your POJOs.  The following file, <code>xfire-servlet.xml</code>, contains a little of both:</p>
<pre>
&lt;beans&gt;

 &lt;!--  add your beans here --&gt;
<strong> &lt;bean id=&#8221;annotatedAuthorService&#8221;
     class=&#8221;com.memestorm.ws.AuthorServiceImpl&#8221;/&gt;</strong>
 &lt;!&#8211;  fin  &#8211;&gt;

 &lt;bean id=&#8221;webAnnotations&#8221;
     class=&#8221;org.codehaus.xfire.annotations.jsr181.Jsr181WebAnnotations&#8221;/&gt;
 &lt;bean id=&#8221;handlerMapping&#8221;
     class=&#8221;org.codehaus.xfire.spring.remoting.Jsr181HandlerMapping&#8221;&gt;
        &lt;property name=&#8221;typeMappingRegistry&#8221;&gt;
            &lt;ref bean=&#8221;xfire.typeMappingRegistry&#8221;/&gt;
        &lt;/property&gt;
        &lt;property name=&#8221;xfire&#8221;&gt;
            &lt;ref bean=&#8221;xfire&#8221;/&gt;
        &lt;/property&gt;
        &lt;property name=&#8221;webAnnotations&#8221;&gt;
            &lt;ref bean=&#8221;webAnnotations&#8221;/&gt;
        &lt;/property&gt;
 &lt;/bean&gt;

 &lt;bean class=&#8221;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&#8221;&gt;
        &lt;property name=&#8221;urlMap&#8221;&gt;
            &lt;map&gt;
                &lt;entry key=&#8221;/&#8221;&gt;
                    &lt;ref bean=&#8221;handlerMapping&#8221;/&gt;
                &lt;/entry&gt;
            &lt;/map&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;import resource=&#8221;classpath:org/codehaus/xfire/spring/xfire.xml&#8221;/&gt;

&lt;/beans&gt;</pre>
<p>The lines in bold are the only ones that matter to us - it exposes our bean implemented by <code>com.memestorm.ws.AuthorServiceImpl</code>.  The rest configures XFire to use annotations in the first place and sets up some defaults.  You will want to come back here when you do more advanced stuff such as type mappings.</p>
<p><strong>2. Configuring the XFire Servlet</strong></p>
<p>As you&#8217;ve seen, we&#8217;ve got this <code>xfire-servlet.xml</code> context configuration file. You&#8217;ll want to tell Spring about it, and as we&#8217;ve shown before, you can do this by modifying the <code>contextConfigLocation</code> context parameter in <code>web.xml</code>:</p>
<pre>
 &lt;context-param&gt;
   &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
   &lt;param-value&gt;
     /WEB-INF/applicationContext.xml /WEB-INF/jdbcContext.xml
     <strong>/WEB-INF/xfire-servlet.xml</strong>
   &lt;/param-value&gt;
 &lt;/context-param&gt;</pre>
<p>You also need to add the following lines:</p>
<pre>
   &lt;servlet&gt;
     &lt;servlet-name&gt;XFireServlet&lt;/servlet-name&gt;
     &lt;servlet-class&gt;
       org.codehaus.xfire.spring.XFireSpringServlet
     &lt;/servlet-class&gt;
   &lt;/servlet&gt;
   &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;XFireServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/servlet/XFireServlet/*&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;
   &lt;servlet-mapping&gt;
     &lt;servlet-name&gt;XFireServlet&lt;/servlet-name&gt;
     &lt;url-pattern&gt;/services/*&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;</pre>
<p>That simply ensures that XFire is deployed as a servlet.</p>
<p><strong>3. Build</strong></p>
<p>XFire has an astounding array of dependencies - and you only need some under various circumstances.  Here&#8217;s how I had to modify the build file to account for this:</p>
<ul>
<li>Modify the <code>master-classpath</code> so that I had the right JARs in my path to compile everything:
<pre> &lt;fileset dir="${xfire.root}"&gt;
   &lt;include name="xfire-all-1.1.jar" /&gt;
 &lt;/fileset&gt;
 &lt;fileset dir="${xfire.root}/lib"&gt;
   &lt;include name="xfire-jsr181-api-1.0-M1.jar" /&gt;
 &lt;/fileset&gt;</pre>
</li>
<li>Modify the <code>libraries</code> target to ensure all run-time JARs are available:
<pre>
&lt;fileset dir="${xfire.root}"&gt;
  &lt;include name="xfire-all-1.1.jar" /&gt;
&lt;/fileset&gt;
&lt;fileset dir="${xfire.root}/lib"&gt;
  &lt;include name="stax-api-1.0.1.jar" /&gt;
  &lt;include name="xfire-jsr181-api-1.0-M1.jar" /&gt;
  &lt;include name="activation-1.1.jar" /&gt;
  &lt;include name="mail-1.4.jar" /&gt;
  &lt;include name="jaxen-1.1-beta-8.jar" /&gt;
  &lt;include name="jdom-1.0.jar" /&gt;
  &lt;include name="wsdl4j-1.5.2.jar" /&gt;
  &lt;include name="wstx-asl-2.9.3.jar" /&gt;
&lt;/fileset&gt;</pre>
</li>
</ul>
<p>Okay, I admit there is a little pain here.  But you only need to do this once of course, and you are deploying an awesome Web service stack that will bring you hours of pleasure&#8230;</p>
<p><strong>4. Running it</strong></p>
<p>That&#8217;s it though - grab the source below, run build, deploy, and you&#8217;ll have exposed the web service.  The XFire servlet provides a nice way to view the deployed Web services too.  If you go to <a href="http://localhost:8080/skeleton2/service/">http://localhost:8080/skeleton2/services/</a> you&#8217;ll see:</p>
<pre>
 Services:
  o MyAuthorService [wsdl]</pre>
<p>with a link to the WSDL file.  Viewing the WSDL file you&#8217;ll get the expected output:</p>
<pre>
&lt;wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:soapenc11="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soapenc12="http://www.w3.org/2003/05/soap-encoding" <strong>xmlns:tns=&#8221;http://memestorm.com/skeleton1/AuthorService&#8221;</strong> xmlns:wsdlsoap=&#8221;http://schemas.xmlsoap.org/wsdl/soap/&#8221; xmlns:xsd=&#8221;http://www.w3.org/2001/XMLSchema&#8221; targetNamespace=&#8221;http://memestorm.com/skeleton1/AuthorService&#8221;&gt;
  &lt;wsdl:types&gt;
    &lt;xsd:schema targetNamespace=&#8221;http://memestorm.com/skeleton1/AuthorService&#8221; elementFormDefault=&#8221;qualified&#8221; attributeFormDefault=&#8221;qualified&#8221;&gt;
      &lt;xsd:element name=&#8221;sayHello&#8221;&gt;
        &lt;xsd:complexType /&gt;
      &lt;/xsd:element&gt;
      &lt;xsd:element name=&#8221;sayHelloResponse&#8221;&gt;
        &lt;xsd:complexType&gt;
          &lt;xsd:sequence&gt;
            &lt;xsd:element name=&#8221;out&#8221; type=&#8221;xsd:string&#8221; nillable=&#8221;true&#8221; minOccurs=&#8221;1&#8243; maxOccurs=&#8221;1&#8243; /&gt;
          &lt;/xsd:sequence&gt;
        &lt;/xsd:complexType&gt;
      &lt;/xsd:element&gt;
    &lt;/xsd:schema&gt;

&#8230;&#8230;

  &lt;wsdl:service name=&#8221;<strong>MyAuthorService</strong>&#8220;&gt;
    &lt;wsdl:port binding=&#8221;tns:MyAuthorServiceHttpBinding&#8221; name=&#8221;MyAuthorServiceHttpPort&#8221;&gt;
      &lt;wsdlsoap:address location=&#8221;http://localhost:8080/skeleton1/services/MyAuthorService&#8221; /&gt;
    &lt;/wsdl:port&gt;
  &lt;/wsdl:service&gt;
&lt;/wsdl:definitions&gt;</pre>
<p>Nice huh? No hassle Web services&#8230;</p>
<h4>A Client</h4>
<p>Okay, here&#8217;s a client that you can run against the Web service.  Read the XFire documentation to learn more about it if you like:</p>
<pre>
package com.memestorm.ws.client;

import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.annotations.AnnotationServiceFactory;
import com.memestorm.ws.*;

import java.net.MalformedURLException;

public class Test {
	public static void main(String[] args) {
		Service serviceModel = new AnnotationServiceFactory()
				.create(AuthorServiceImpl.class);
		try {
			AuthorService service = (AuthorService) new XFireProxyFactory().create(
					serviceModel,
					"http://localhost:8080/skeleton1/services/MyAuthorService");
			String s = service.sayHello();
			System.out.println(s);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

	}
}</pre>
<h4>Summary</h4>
<p>What we&#8217;ve done here is set up a scenario where you can easily expose POJOs as Web services using JSR 181 standard annotations.  These are standard annotations that you&#8217;ll find in Java EE 5 - so it&#8217;s pretty nice to be able to use them here in the XFire Web services stack.</p>
<p>Moreover, this scenario is hooked into our Spring web application.  We can trivially add additional POJOs, and use the full Spring toolbox to manipulate them.</p>
<h4>Download</h4>
<p>Here&#8217;s a JAR of all the source, with instructions on how to build and deploy:<br />
<a href="http://www.memestorm.com/blog/wp-content/uploads/2006/05/skeleton2-1.zip">skeleton2-1.zip</a></p>
<h4>Acknowledgements</h4>
<p>I&#8217;d like to reference the <a href="http://www.logemann.org/blojsom/blog/default/2006/05/26/Webservices-with-Spring-XFire-and-jsr181.html">Logemann Blog that showed me how to do most of this stuff.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/basic-spring-web-services-with-xfire-and-jsr-181/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Spring Components - XML configuration on steroids</title>
		<link>http://www.memestorm.com/blog/spring-components-xml-configuration-on-steroids/</link>
		<comments>http://www.memestorm.com/blog/spring-components-xml-configuration-on-steroids/#comments</comments>
		<pubDate>Thu, 30 Mar 2006 04:44:34 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject><dc:subject>configuration</dc:subject><dc:subject>ioc</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/spring-components-xml-configuration-on-steroids/</guid>
		<description><![CDATA[The single most important feature in Spring 2.0 (IMO) is a new XML
configuration convenience feature.  I believe this is going to
revolutionize the way people develop for Spring and bootstrap a modest
component market too.  This is a lot more than a convenience features
- it&#8217;s a fledgling component model too.
In the &#8216;old&#8217; Spring configuration files, [...]]]></description>
			<content:encoded><![CDATA[<p>The single most important feature in Spring 2.0 (IMO) is a new XML<br />
configuration convenience feature.  I believe this is going to<br />
revolutionize the way people develop for Spring and bootstrap a modest<br />
component market too.  This is a lot more than a convenience features<br />
- it&#8217;s a fledgling component model too.</p>
<p>In the &#8216;old&#8217; Spring configuration files, almost everything was a bean.  That is, you would write:</p>
<pre>
&lt;bean id="foo" class="bar"&gt;
   &lt;!-- zip zip --&gt;
&lt;/bean&gt;</pre>
<p>In fact, if you look at the DTD you&#8217;ll see why:</p>
<pre>
&lt;!ELEMENT beans (
	description?,
	(import | alias | bean)*
)&gt;</pre>
<p>In Spring 2 (I&#8217;m using M3) you can do something altogether different:</p>
<pre>
 &lt;mycomponent:foobar att="zip"/&gt;</pre>
<p>Note that there is no <code>class</code> attribute - all the necessary information is captured behind the namespace.  If you look at it from an XML configuration point of view, what this provides is a way of avoiding laboriously repetitive bean definitions by capturing beans in their own namespace.  Spring comes with a number of these already defined:</p>
<pre>
 &lt;jndi:lookup id="dataSource" jndiName="jdbc/MyDS"/&gt;
 &lt;tx:advice id="txAdvice"&gt;
   &lt;tx:attributes&gt;
     &lt;tx:method name="insert*"/&gt;
     &lt;tx:method name="update*"/&gt;
     &lt;tx:method name="*" read-only="true"/&gt;
   &lt;/tx:attributes&gt;
 &lt;/tx:advice&gt;</pre>
<p>However, now think of the possibilities:</p>
<ul>
<li>You can simplify configuration (as we&#8217;ve just seen)</li>
<li>You can hide implementation (all the &#8216;user&#8217; needs to see is the namespace)</li>
<li>You can start distributing &#8216;Spring Components&#8217; that folk can simply plug in by adding the JAR and referencing them from your application context!</li>
</ul>
<p>I think it&#8217;s the last two points that are the most exciting.  They&#8217;re perhaps not what the Spring developers intended, but they are the start of something new.  You can now distribute a simple JAR that contains all your Spring beans that do something, say interface with Amazon, together with an XML schema describing those beans that you want to make public.  Any user of this &#8216;Spring Component&#8217; simply installs this JAR and starts typing:</p>
<pre>
&lt;amazon:listBooks conditionSubject='memetics' associateId='memestorm'/&gt;</pre>
<p>You can even bung view tier stuff into beans, so the future is wide open.</p>
<h4>How to do it</h4>
<p>Let&#8217;s look at how you can roll your own component, resulting in a<br />
simple JAR that you can distribute.  See the attachment for a deployable<br />
example: <code>simple.jar</code>.  If this is in your application&#8217;s classpath, for example deployed in <code>WEB-INF/lib</code> then at the end of the day, all you need to do is wire it into your application context.</p>
<p><strong>Wiring in the component</strong></p>
<pre>
&lt;beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   <strong> xmlns:memestorm=&#8221;http://www.memestorm.com/schema/simple&#8221;</strong>
    xsi:schemaLocation=&#8221;http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
<strong>    http://www.memestorm.com/schema/simple
     http://www.memestorm.com/schema/simple/spring-simple.xsd&#8221;</strong>&gt;

<strong>  &lt;memestorm:action id=&#8221;s&#8221; value=&#8221;HelloWorld&#8221; /&gt;</strong>

  &lt;bean id=&#8221;foo&#8221;&gt;
    &lt;!&#8211; .. &#8211;&gt;
  &lt;/bean&gt;
  &lt;!&#8211; other definitions &#8211;&gt;

&lt;/beans&gt;</pre>
<p>Notice that I&#8217;m using the XML Schema version of the bean configuration instead of DTD, and that I&#8217;ve defined my <code>memestorm</code> component as a namespace mapped to <code>http://www.memestorm.com/schema/simple</code>.  We&#8217;ll later see how this name space gets mapped to a bean.</p>
<p><strong>Coding the component</strong></p>
<p>That&#8217;s it as far as the client goes.  Just add the JAR and wire it in.  Let&#8217;s look at the implementation.  Instead of an Amazon component, we&#8217;ve written a rather simpler <code>Simple</code> component:</p>
<pre>
package com.memestorm.beandemo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SimpleBean {
   private String value;
   private String otherValue;

   Log logger = LogFactory.getLog(getClass());

   public SimpleBean () {
      logger.error("In the constructor of SimpleBean");
   }

   public void action() {
      logger.error("In action with value='" + value + "' and otherValue='" + otherValue + "'");
   }

   public String getValue() {
      return value;
   }

   public void setValue(String value) {
      this.value = value;
   }

   public String getOtherValue() {
      return otherValue;
   }

   public void setOtherValue(String otherValue) {
      this.otherValue = otherValue;
   }
}</pre>
<p>As you can see, it has two properties (<code>value</code>, <code>otherValue</code>) and its constructor and <code>action()</code> method both log messages.  (So to use the component, you need commons-logging in your app!)</p>
<p><strong>Defining its XML interface</strong></p>
<p>As you saw in the wiring, the XML interface is defined by an XML schema.  So we need to define an XML schema that should be adhered to by clients of our component.  Here is one we created, <code>simple.xsd</code>:</p>
<pre>
&lt;xsd:schema xmlns="http://www.memestorm.com/schema/simple"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         targetNamespace="http://www.memestorm.com/schema/simple"
         elementFormDefault="qualified"
         attributeFormDefault="unqualified"&gt;
   &lt;xsd:element name="action"&gt;
      &lt;xsd:complexType&gt;
         &lt;xsd:attribute name="id" type="xsd:ID" use="required"/&gt;
         &lt;xsd:attribute name="value" type="xsd:string"/&gt;
      &lt;/xsd:complexType&gt;
   &lt;/xsd:element&gt;
&lt;/xsd:schema&gt;</pre>
<p>As you can see, it simply permits two attributes to an element called <code>action</code>.  Look back to &#8216;Wiring in the component&#8217; and you&#8217;ll see it all fits together.</p>
<p><strong>The Namespace Handler</strong></p>
<p>Behind the scenes, Spring invokes a namespace handler to create the actual bean instance from something like:</p>
<pre>
&lt;memestorm:action id="s" value="HelloWorld" /&gt;</pre>
<p>As a component developer, you have to supply this namespace handler.  Here is our implementation:</p>
<pre>
package com.memestorm.tag;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.w3c.dom.Element;
import com.memestorm.beandemo.SimpleBean;

public class SimpleNamespaceHandler extends NamespaceHandlerSupport {

  public SimpleNamespaceHandler() {
<strong>    registerBeanDefinitionParser(&#8221;action&#8221;, new SimpleBeanDefinitionParser());</strong>
  }

  private static class SimpleBeanDefinitionParser extends
      AbstractSimpleBeanDefinitionParser {

    protected Class getBeanClass(Element element) {
      return SimpleBean.class;
    }

    protected void postProcess(BeanDefinitionBuilder definitionBuilder,
        Element element) {
      definitionBuilder.addPropertyValue(&#8221;otherValue&#8221;, &#8220;fromPostProcess&#8221;);
      definitionBuilder.setInitMethodName(&#8221;action&#8221;);
    }
  }
}</pre>
<p>Note that the constructor registers a bean definition parser, associating it with an element. You&#8217;ll later see how we map the namespace to the element.  The bean definition parser itself is pretty simple.  <code>getBeanClass()</code> should return the appropriate class - as you can see we return <code>SimpleBean.clas</code>.  We also have a <code>postProcess()</code> method that you can use to add to the parsed bean definition.  In this case we set another property value and we set the <code>init-method</code> to be invoked.  What&#8217;s happening behind the scenes here, in <code>AbstractSimpleBeanDefinitionParser</code>, is that the XML snippet is parsed and all of its attributes (and values) are mapped to setters of properties on the bean instance (except for <code>id</code>).  In other words, its programmatically creating the bean definition and its properties according to the values defined in the application context.</p>
<p><strong>Packaging</strong></p>
<p>To package everything, simply include all the XSD files, beans, and namespace handlers into a JAR with two special files in the <code>META-INF</code> directory.  First you need <code>spring.schemas</code>:</p>
<pre>
http://www.memestorm.com/schema/simple/spring-simple.xsd=com/memestorm/tag/simp
le.xsd</pre>
<p>As you can see, this maps the namespace location to the physical location of the schema in the JAR.  Next, you need <code>spring.handlers</code>:</p>
<pre>
http://www.memestorm.com/schema/simple=com.memestorm.tag.SimpleNamespaceHandler</pre>
<p>As you can see, this maps the schema namespace to the tag handler.  That&#8217;s it.</p>
<h4>Summary</h4>
<p>In summary then:</p>
<ul>
<li>Create the XML schema defining your component</li>
<li>Create your component bean/beans</li>
<li>Create a namespace handler that maps the schema to the beans</li>
<li>Create two packaging artifacts to tie it all together</li>
</ul>
<h4>Download</h4>
<p>Here&#8217;s a deployable JAR with source (of course, you need to deploy to a Spring 2 M3 application, with commons-logging available too).</p>
<p><a href="http://www.memestorm.com/blog/wp-content/uploads/2006/03/simple.jar">simple.jar</a></p>
<a href="http://www.memestorm.com/blog/index.php?tag=configuration" rel="tag">configuration</a>  <a href="http://www.memestorm.com/blog/index.php?tag=ioc" rel="tag">ioc</a>]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/spring-components-xml-configuration-on-steroids/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Convention over Configuration in Spring&#8217;s MVC</title>
		<link>http://www.memestorm.com/blog/convention-over-configuration-in-springs-mvc/</link>
		<comments>http://www.memestorm.com/blog/convention-over-configuration-in-springs-mvc/#comments</comments>
		<pubDate>Fri, 17 Mar 2006 18:13:06 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/convention-over-configuration-in-springs-mvc/</guid>
		<description><![CDATA[Convention over Configuration in Spring's MVC, the ControllerClassNameHandlerMapping.]]></description>
			<content:encoded><![CDATA[<p><em>Convention Over Configuration</em> (CoC) is a term often bandied<br />
around by Ruby on Rails followers.  From the <a href="http://en.wikipedia.org/wiki/Ruby_on_rails">wikipedia</a> it&#8217;s<br />
defined as &#8220;the programmer only needs to specifically configure what<br />
is unconventional.&#8221;  Very sensible advice indeed, although it&#8217;s not <a href="http://www.dehora.net/journal/2005/11/convention_over_configuration.html">without its problems</a>.  We&#8217;ve <a href="http://www.memestorm.com/blog/basic-web-mvc-example/">already<br />
seen one example</a> of CoC in Spring: the use of<br />
<code>InternalResourceViewResolver</code> effectively lets programmers<br />
forget about configuring resource views for incoming URLs, and instead<br />
rely on the convention of mapping to a like-named view (it extracts<br />
the view name from the URL).  In fact, the <code>MultiActionController</code> is a type of CoC too - you don&#8217;t have to configure an action name; Spring tries to automatically invoke a like-named method on the controller class based on the URL. (The <code>MethodNameResolver</code> actually.)  These two essentially enforce the convention of automatically selecting a view, and a method in a controller class respectively.</p>
<p>Now let&#8217;s look at a third example of CoC: <code>ControllerClassNameHandlerMapping</code>. This enforces the convention of automatically selecting a controller.</p>
<h4>Background</h4>
<p>As shown in <a href="http://www.memestorm.com/blog/simple-url-mapping-and-factory-beans-in-spring/">Simple URL Mapping&#8230;</a>, a URL Mapper has to map incoming URL requests to particular controllers.  Typically we have to configure the URL mapper with each new controller that we add.  Turning this on its head, we want to use CoC so that the convention is that the correct controller is automatically selected if it&#8217;s registered, without any configuration.</p>
<h4>How to do it</h4>
<p>Simply use the <code>ControllerClassNameHandlerMapping</code> as your URL mapper in your <code>dispatch-servlet.xml</code> configuration file.  For example:</p>
<pre>
&lt;bean id="urlMapping"
  class="org.springframework.web.servlet.mvc.ControllerClassNameHandlerMapping"&gt;
&lt;/bean&gt;</pre>
<p>Define your controllers as usual.  For example, I have this:</p>
<pre>
&lt;bean id="commandController"
   class="com.memestorm.web.CommandController"&gt;
&lt;/bean&gt;</pre>
<p>That&#8217;s it.  You don&#8217;t have to wire your controllers to URLs, this is now automated.  Now instead of explicitly configuring mappings between URLs and controllers, you can rely on the convention, which is to take the <code>ClassUtils.getShortName()</code> name of the controller class, remove the &#8220;Controller&#8221; suffix if it exists and the cap, and use the result as a mapping.  For example our <code>CommandController</code> would be mapped to <code>/command/</code>.</p>
<p>For <code>MultiActionController</code> controllers (see our <a href="http://www.memestorm.com/blog/basic-web-mvc-example/">recent example</a>) it works slightly differently.  In this case, say for our <code>DispatchController</code> example, it will map <code>/dispatch/*</code> to the controller. (Note the extra wildcard).</p>
<p>Now you can concentrate on writing your controllers and action methods.  Everything will be automatically wired in; nice.</p>
<h4>How it works</h4>
<p>It&#8217;s actually dead simple.  The <code>ControllerClassNameHandlerMapping</code> class simply iterates through the application context looking for beans of type <code>Controller</code>, adding them to the mapping as described earlier.</p>
<h4>Acknowledgements</h4>
<p>Thanks to Matt for <a href="http://jroller.com/page/raible/20060217">highlighting this class</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/convention-over-configuration-in-springs-mvc/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Spring Binding and Validation: Introduction</title>
		<link>http://www.memestorm.com/blog/spring-binding-and-validation-introduction/</link>
		<comments>http://www.memestorm.com/blog/spring-binding-and-validation-introduction/#comments</comments>
		<pubDate>Mon, 20 Feb 2006 14:03:17 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/spring-binding-and-validation-introduction/</guid>
		<description><![CDATA[You want to slurp in some data, perhaps from a simple form or from
request parameters.  To do this, we'll explore the <code>AbstractCommandController</code> and learn about the related issues of binding and validation.  Spring makes this kind of thing pretty effortless, and this will serve as the foundation of exploring more advanced form-handling.]]></description>
			<content:encoded><![CDATA[<p>You want to slurp in some data, perhaps from a simple form or from<br />
request parameters.  To do this, we&#8217;ll explore the <code>AbstractCommandController</code> and learn about the related issues of binding and validation.  Spring makes this kind of thing pretty effortless, and this will serve as the foundation of exploring more advanced form-handling.</p>
<h4>How to do it</h4>
<p>The controllers we wrote about in previous blog entries, such as the <code>MultiActionController</code>, are generally used for carrying out actions.  What if you wanted to rather input some data first, perhaps through request parameters?  Well one way to do this is the hard way:</p>
<pre>
String val = (String) request.getParameter("someParamName");</pre>
<p>Those were the days.  Untyped, inflexible, error-prone, with all sorts of casting (imagine if I wanted a date or an integer).</p>
<p>A much better approach use <em>data binding</em> - let Spring bind the incoming data to a Plain Old JavaBean (POJO) for you - then you can simply use that POJO as you&#8217;d expect.  Spring calls these beans <em>commands</em>, which I think is a bit of a misnomer, but there you go.  Let&#8217;s see this in action.  First, we&#8217;re going to modify our <code>dispatch-servlet.xml</code> configuration file to include a new controller:</p>
<pre>
&lt;bean id="commandController"
  class="com.memestorm.web.CommandController"&gt;
&lt;/bean&gt;</pre>
<p>Now let&#8217;s modify our handler mappings (see previous blog entries if you need to understand these) to include a mapping to our command controller:</p>
<pre>
/cmd=commandController
/*=dispatchController</pre>
<p>So in theory now, something like <code>http://localhost:8080/send/cmd?age=10</code> will get sent to our command controller.  Now the command controller we&#8217;ll use is the simplest around.  It extends the <code><a href="http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/AbstractCommandController.html">AbstractCommandController</a></code>.  Here&#8217;s the code:</p>
<pre>
public class CommandController extends AbstractCommandController {

  public CommandController() {
<strong>    setCommandClass(SimpleCommand.class);</strong>
  }

  protected ModelAndView handle(HttpServletRequest request,
		HttpServletResponse response, Object command,
                BindException errors) throws Exception {

    SimpleCommand cmd = (SimpleCommand) command;

    PrintWriter pw = response.getWriter();
    pw.println(cmd);
    return null;
  }
}</pre>
<p>The first thing you&#8217;ll notice (probably because I have it in bold) is that the constructor calls <code>setCommandClass()</code> with the class that will hold the incoming values.  This is the <em>command class</em> I spoke about earlier.  All incoming parameters are mapped onto this class, automatically, for you.  We pass the <code>setCommandClass()</code> the class so that it can instantiate a new instance every time the controller is invoked.  Now take a look at the <code>handle()</code> method, somewhat more complicated than the others that we&#8217;ve seen in <a href="http://www.memestorm.com/blog/basic-web-mvc-example/">Basic Spring Web MVC Example</a>.  The two extra parameters are the command (which Spring will have created and populated for you), and an object listing errors (which we&#8217;ll describe later).</p>
<p>The method is pretty simple: It casts the command object to the expected type, and then writes it to the response.  Let&#8217;s look at the command object:</p>
<pre>
public class SimpleCommand {
 Integer age;
 String name;

 public String getName() {return name;}

 public void setName(String name) {this.name = name;}

 public Integer getAge() {return age;}

 public void setAge(Integer age) {this.age = age;}

 public String toString() {
   return "Name=[" + this.name + "], Age=[" + this.age + "]";
 }
}</pre>
<p>You must admit, that&#8217;s pretty straightforward. A typed container, just ready to be populated by incoming values.  Now, if you invoke something like <code>http://localhost:8080/skeleton3/send/cmd?name=Jon&amp;age=30</code> you&#8217;ll see the output as <code>Name=[Jon], Age=[30]</code>.  This is pretty darn nice for a number of reasons:</p>
<ul>
<li>Notice that I didn&#8217;t write any code to bind the incoming parameters to the command bean.  It&#8217;s automatic.</li>
<li>Notice that the command bean is typed - <code>getAge()</code> returns an Integer and somehow Spring converted the incoming field to the appropriate type automatically.</li>
</ul>
<p>This is a considerable step up from <code>getRequestParameter()</code>.  It even works for a form input.  For example, here is a simple form that you can use to invoke our controller:</p>
<pre>
&lt;form action="send/cmd" method="post"&gt;
 Name: &lt;input type="text" name="name" /&gt;
 Age: &lt;input type="text" name="age" /&gt;
&lt;/form&gt;</pre>
<p>But wait, there&#8217;s more!  If we extend our <code>handler()</code> method to dump some information found in the <code>errors</code> parameter, we&#8217;ll see further magic:</p>
<pre>
pw.println("&lt;hr&gt;" + "Error count=" + errors.getErrorCount());
pw.println("&lt;br&gt;Errors for age field"  + errors.getFieldErrors("age"));
pw.println("&lt;br&gt;Input value for age field: " + errors.getFieldValue("age"));
pw.println("&lt;br&gt;" + errors.getGlobalErrors());</pre>
<p>Now if we invoke it with an error in the age value (for example, some letters instead of digits) as in:  <code>http://localhost:8080/skeleton3/send/cmd?name=Jon&amp;age=crikey</code> we&#8217;ll see the following output:</p>
<pre>
Name=[Jon], Age=[null]
&lt;hr&gt;Error count=1
&lt;br&gt;Errors for age field[Field error in object 'command' on field 'age': rejected value [crikey]; codes [typeMismatch.command.age,typeMismatch.age,typeMismatch.java.lang.Integer,typeMismatch]; arguments [MessageSourceResolvable: codes [command.age,age]; arguments []; default message [age]]; default message [Failed to convert property value of type [java.lang.String] to required type [java.lang.Integer] for property 'age'; nested exception is java.lang.NumberFormatException: For input string: "crikey"]]
&lt;br&gt;Input value for age field: crikey</pre>
<p>Now notice that the age value is <code>null</code> (it can&#8217;t convert &#8216;crikey&#8217;), notice that we have an error count, that we have access to the original text that the user entered, and we have a good error message too.  That&#8217;s a lot of magic for very little effort.</p>
<p>But wait, there&#8217;s even more.  With a simple change to the constructor, we can validate input values too.  Here is an example modification:</p>
<pre>
public CommandController() {
  setCommandClass(SimpleCommand.class);
  <strong>setValidator(new Validator(){
    public boolean supports(Class clazz) {
      return (clazz.equals(SimpleCommand.class));
    }
    public void validate(Object command, Errors errors) {
      SimpleCommand incoming = (SimpleCommand) command;
      ValidationUtils.rejectIfEmpty(errors, &#8220;age&#8221;, &#8220;required.age&#8221;);
      if (incoming.getAge() != null &amp;&amp; incoming.getAge() &gt; 30)
        errors.reject(&#8221;over.the.hill&#8221;, &#8220;too old&#8221;);
   }})</strong>;
}</pre>
<p>As you can see, we&#8217;ve set a <em>validator</em>.  A validator simply implements the <code>Validator</code> interface—here we&#8217;ve done it with a simple anonymous class.  You can instead write full classes for the validators and wire them in with the web context instead - in that way you can promote some reuse with your validators too.  The validator interface has two methods.  <code>supports()</code> tells the system what kind of class it validates.  The <code>validate</code> method performs the actual validation.  We make use of <code>ValidationUtils</code> to ensure that the age is not empty.  You can, instead, write your own validation as we do checking that the age is not too high.  So now, if we pass in an age of 34 say, we&#8217;ll get the following output:</p>
<pre>
...
[Error in object 'command': codes [over.the.hill.command,over.the.hill]; arguments []; default message [too old]]</pre>
<p>There is in fact a little more magic too (message interpretation) but that will have to wait for another day.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/spring-binding-and-validation-introduction/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Loading resources from files or the classpath</title>
		<link>http://www.memestorm.com/blog/loading-resources-from-files-or-the-classpath/</link>
		<comments>http://www.memestorm.com/blog/loading-resources-from-files-or-the-classpath/#comments</comments>
		<pubDate>Sun, 19 Feb 2006 18:48:07 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject><dc:subject>config</dc:subject><dc:subject>utils</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/loading-resources-from-files-or-the-classpath/</guid>
		<description><![CDATA[How to load resources from the file system or classpath from within beans initialized by a Spring context.]]></description>
			<content:encoded><![CDATA[<p>You want to load resources from the file system or classpath from<br />
within beans initialized by a Spring context.</p>
<h4>Background</h4>
<p>Our <code>HSQLDB</code> utility class needs to load the SQL to create the database every time our application starts, as outlined in a <a href="http://www.memestorm.com/blog/embedded-database-spring/">Embedded Database Starting Up With Web Context</a>.  How does this bean get access to the file?  Well, in the context configuration we supplied a file location, for example:</p>
<pre>
&lt;bean id="databaseUtils" class="com.memestorm.utils.db.HSQLDB"&gt;
  &lt;property name="<b>location</b>&#8220;&gt;
    &lt;value&gt;/db/init.sql&lt;/value&gt;
  &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>So, how can we actually get to the file? </p>
<h4>How to do it</h4>
<p>The easiest way is to have your bean implement the <code><a href="http://www.springframework.org/docs/api/org/springframework/context/ResourceLoaderAware.html">ResourceLoaderAware</a></code> interface.  This will then ensure that the <code>setResourceLoader(ResourceLoader resourceLoader)</code> method will get called on your bean, with a magic resource loader. (Look <a href="http://www.memestorm.com/blog/embedded-database-spring/">here</a> for more information on the <em>aware</em> interfaces.)</p>
<p>The <code><a href="http://www.springframework.org/docs/api/org/springframework/core/io/ResourceLoader.html">ResourceLoader</a></code><br />
class is a fantastic utility class provided by Spring, that allows you<br />
to load resources from all sorts of locations.  Given the location above, the resource loader will look for the file <code>db/init.sql</code> relative to the root of the web application (when used from a web context).  Our bean simply uses the location as follows:</p>
<pre>Resource sql = this.resourceLoader.getResource(this.location);
JdbcTemplate jt = new JdbcTemplate(this.dataSource);
jt.execute(IOUtils.toString(sql.getInputStream()));
</pre>
<p>It&#8217;s so simply it belies how easy this makes life!  To load from an arbitrary file location, use the <code>file:</code> prefix instead.  For example,  <code>file:///temp/foobar.sql</code>.  You can also try and locate something in the classpath using the <code>classpath</code> prefix.  For example, <code>classpath:config.xml</code>.  </p>
<p>Have fun.</p>
<a href="http://www.memestorm.com/blog/index.php?tag=config" rel="tag">config</a>  <a href="http://www.memestorm.com/blog/index.php?tag=utils" rel="tag">utils</a>]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/loading-resources-from-files-or-the-classpath/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Use Spring&#8217;s bean lifecycle callback methods to control your destiny</title>
		<link>http://www.memestorm.com/blog/use-springs-bean-lifecycle-callback-methods-to-control-your-destiny/</link>
		<comments>http://www.memestorm.com/blog/use-springs-bean-lifecycle-callback-methods-to-control-your-destiny/#comments</comments>
		<pubDate>Sun, 19 Feb 2006 18:12:20 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
		
	<dc:subject>All</dc:subject><dc:subject>ioc</dc:subject>
		<guid isPermaLink="false">http://www.memestorm.com/blog/use-springs-bean-lifecycle-callback-methods-to-control-your-destiny/</guid>
		<description><![CDATA[You want to run an initialize or destroy method on a bean after the Spring context creates it. These lifecycle methods allow you to grab and release resources.]]></description>
			<content:encoded><![CDATA[<p>You want to run an initialize or destroy method on a bean after the context creates it. These lifecycle methods allow you to grab and release resources.</p>
<h4>How to do it</h4>
<p>Well, we did this in the <a href="http://www.memestorm.com/blog/embedded-database-spring/">previous blog entry</a>, making use of an <code>ApplicationListener</code> and <code>InitializingBean</code>.  This was overkill!  There&#8217;s a better way that doesn&#8217;t require these interfaces.  To have a method execute after the bean is initialized, or just before it&#8217;s destroyed (ie. at context start up or shutdown), simply modify your configuration file as follows:</p>
<pre>
&lt;bean id="databaseUtils" class="com.memestorm.utils.db.HSQLDB"
  <strong>init-method=&#8221;initialize&#8221; destroy-method=&#8221;destroy&#8221;</strong>&gt;
&lt;/bean&gt;</pre>
<p>You can of course omit either one, or both, of these attributes.  The values of the attributes indicate the method that should be invoked.  So for example, given the above definition the <code>initialize()</code> and <code>destroy()</code> method of the <code>HSQLDB</code> object will be invoked.  This is great, and avoids any dependence on Spring interfaces.</p>
<p>If you&#8217;d like the same functionality relying on interfaces instead, then simply have the class implement <code><a href="http://www.springframework.org/docs/api/org/springframework/beans/factory/InitializingBean.html">InitializingBean</a></code> and <code><a href="http://www.springframework.org/docs/api/org/springframework/beans/factory/DisposableBean.html">DisposableBean</a></code> instead.  In this case the configuration file will not have a <code>init-method</code> or <code>destory-method</code> attribute.</p>
<a href="http://www.memestorm.com/blog/index.php?tag=ioc" rel="tag">ioc</a>]]></content:encoded>
			<wfw:commentRss>http://www.memestorm.com/blog/use-springs-bean-lifecycle-callback-methods-to-control-your-destiny/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
