<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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>spring-framework &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/spring-framework/</link>
	<description>Feed of posts on WordPress.com tagged "spring-framework"</description>
	<pubDate>Sat, 30 Aug 2008 08:03:30 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Spring JMS]]></title>
<link>http://stacktrace.se/?p=212</link>
<pubDate>Wed, 27 Aug 2008 08:06:41 +0000</pubDate>
<dc:creator>Tommy Wassgren</dc:creator>
<guid>http://stacktrace.se/?p=212</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och behandlar några av de delar inom Spring som ]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och behandlar några av de delar inom Spring som hanterar mottag och publicering av JMS-meddelanden.</p>
<p><!--more--><br />
Typiskt när det gäller JMS så vill man kunna:</p>
<ul>
<li>Publicera meddelanden</li>
<li>Ta emot meddelanden asynkront</li>
</ul>
<p>Om man inte använder Spring så brukar man lösa detta genom att:</p>
<ul>
<li>Publicera meddelanden via JMS-API:et</li>
<li>Ta emot meddelanden via MDB (Message Driven Beans)</li>
</ul>
<h2>Publicering av meddelanden</h2>
<p>Problemet med att använda JMS-API:et för att publicera meddelanden är att det blir mycket onödig kod som måste skrivas. Checkade exceptions måste hanteras, en rad objekt såsom connection factory, session, destinations etc. måste sparas undan, om JMS-kopplingen går ner så måste hantering för "re-connect" byggas etc.</p>
<p>Klassen <code>JmsTemplate</code> är den centrala klassen för publicering av meddelanden. Denna klass baserar på designmönstret <a href="http://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">template method</a> som tidigare beskrivits i inlägget om <a href="http://stacktrace.se/2008/08/19/spring-jdbc/">Spring JDBC</a>.</p>
<p>Följande exempel visar hur publicering av meddelanden ser ut om man inte använder <code>JmsTemplate</code> utan går direkt mot JMS API:et</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class RawJmsMessageSender {
    private boolean isTopic;
    private ConnectionFactory connectionFactory;

    public void sendMessage(String destinationName, String messageText) {
        try {
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(
                    true, Session.AUTO_ACKNOWLEDGE);
            Destination destination = createDestination(
                    session, destinationName);
            MessageProducer producer =
                session.createProducer(destination);
            TextMessage message = session.createTextMessage();
            message.setText(messageText);
            producer.send(destination, message);
        } catch (JMSException e) {
            // Do error handling here...
            throw new IllegalStateException("Unable to send message", e);
        }
    }

    private Destination createDestination(
            Session session,
            String destinationName) throws JMSException {

        if (isTopic()) {
            return session.createTopic(destinationName);
        } else {
            return session.createQueue(destinationName);
        }
    }

    public boolean isTopic() {
        return isTopic;
    }

    public void setTopic(boolean isTopic) {
        this.isTopic = isTopic;
    }

    public void setConnectionFactory(
            ConnectionFactory connectionFactory) {

        this.connectionFactory = connectionFactory;
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Publicering via JMS-API</em></strong></td>
</tr>
</tbody>
</table>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="rawJmsMessageSender"
  class="se.cygni.sample.spring.jms.RawJmsMessageSender"&#62;

    &#60;property name="connectionFactory" ref="connectionFactory"/&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>Springkonfiguration för RawJmsMessageSender</em></strong></td>
</tr>
</tbody>
</table>
<p>I exemplet antas att en <code>ConnectionFactory</code> finns tillgänglig. Klassen <code>RawJmsMessageSender</code> kan alltså skicka JMS-meddelanden på en kö eller topic. Exemplet ovan fungerar inte så bra i verkligheten eftersom en ny connection, session och destination skapas varje gång. Ett runtime exception som är helt otypat (<code>IllegalStateException</code>) skapas när ett fel uppstår.</p>
<p>Ovanstående exempel kan förenklas genom att använda <code>JmsTemplate</code>. På köpet får man dessutom möjlighet att använda en bättre felhantering via Springs JMS-exception hierarki och betydligt mindre kod. Kolla in följande för att se hur <code>JmsTemplate</code> kan användas.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class JmsTemplateMessageSender {
    private JmsTemplate jmsTemplate;

    public void sendMessage(
            String destinationName, final String messageText) {

        jmsTemplate.send(destinationName, new MessageCreator() {
            public Message createMessage(
                    Session session) throws JMSException {

                return session.createTextMessage(messageText);
            }
        });
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Publicering med JmsTemplate</em></strong></td>
</tr>
</tbody>
</table>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="jmsTemplateMessageSender"
  class="se.cygni.sample.spring.jms.JmsTemplateMessageSender"&#62;

    &#60;property name="jmsTemplate" ref="jmsTemplate"/&#62;
&#60;/bean&#62;

&#60;bean
  id="jmsTemplate"
  class="org.springframework.jms.core.JmsTemplate"&#62;

    &#60;property name="connectionFactory" ref="connectionFactory"/&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>Springkonfiguration med JmsTemplate</em></strong></td>
</tr>
</tbody>
</table>
<p><code>JmsTemplate</code> tillhandahåller en rad template-metoder och i exemplet ovan används <code>send(String, MessageCreator)</code>. De eventuella exceptions som kan slängas hanteras av <code>JmsTemplate</code>. <code>JmsTemplate</code> kan konfigureras för att använda både köer och topics och många av de attribut som kan konfigureras på sessionen kan konfigureras direkt på template-objektet. Förutom send-metoden finns andra template-metoder, kolla exempelvis in dokumentationen för convertAndSend som kan konvertera en POJO till ett Message via en MessageConverter.</p>
<h2>Mottag av meddelanden</h2>
<p>Vid asynkront mottag av JMS-meddelanden måste interfacet <code>javax.jms.MessageListener</code> implementeras. Message Driven Beans (MDB) implementerar detta interface och när MDB:er används hanterar applikationsservern trådning och transaktionshantering av MDB:n. Om man inte har någon applikationsserver kan Springs Message Driven POJOs (MDP) vara till hjälp för att ta emot meddelanden.</p>
<p>MDP:s implementeras med hjälp av en så kallad ListenerContainer som hanterar trådning och pollar kön/topicen efter meddelanden. De tre varianter som finns är:</p>
<ul>
<li>SimpleMessageListenerContainer<br />
Den enklaste av de tre containrarna. Denna container startar ett förutbestämt antal JMS-sessioner vid uppstart av containern.</li>
<li>DefaultMessageListenerContainer<br />
Ett mellanting mellan SimpleMessageListenerContainer och ServerSessionMessageListenerContainer som erbjuder vissa konfigurationsmöjligheter. Framför allt så kan denna container ingå i transaktioner som hanteras externt via ex. en TransactionManager.</li>
<li>ServerSessionMessageListenerContainer<br />
Denna container kan konfigureras med extern transaktionshantering och användning av ServerSessionPool SPI för hantering av JMS-sessioner.</li>
</ul>
<p>Nedanstående exempel visar hur man enkelt kan sätta upp en MDP som lyssnar på en kö som finns tillgänglig i JNDI-trädet.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class JmsMessageReceiver implements MessageListener {
    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage) message;
        System.out.println("Received message: " + textMessage);
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JMS-mottagare</em></strong></td>
</tr>
</tbody>
</table>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="jndiTemplate"
  class="org.springframework.jndi.JndiTemplate"&#62;

    &#60;property name="environment"&#62;
        &#60;props&#62;
            &#60;prop key="java.naming.factory.initial&#62;vendor stuff&#60;/prop&#62;
        &#60;/props&#62;
    &#60;/property&#62;
&#60;/bean&#62;

&#60;bean
  id="jmsMessageReceiver"
  class="se.cygni.sample.spring.jms.JmsMessageReceiver" /&#62;

&#60;bean
  id="jmsContainer"
  class="org.springframework.jms.listener.DefaultMessageListenerContainer"&#62;

    &#60;property name="connectionFactory" ref="connectionFactory"/&#62;
    &#60;property name="destination" ref="destination"/&#62;
    &#60;property name="messageListener" ref="jmsMessageReceiver" /&#62;
    &#60;property name="concurrentConsumers" value="5" /&#62;
&#60;/bean&#62;

&#60;bean
  id="destination"
  class="org.springframework.jndi.JndiObjectFactoryBean"
  depends-on="connectionFactory"&#62;

    &#60;property name="jndiName" value="myQueue" /&#62;
    &#60;property name="jndiTemplate" ref="jndiTemplate" &#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>Springkonfiguration för JMS-mottagare</em></strong></td>
</tr>
</tbody>
</table>
<p>I exemplet ovan används fem trådar som specificeras via attributet <code>concurrentConsumers</code>. Dessa trådar kommer kontinuerligt att polla JMS-kön som är specificerad via bönan destination. När ett meddelande hittas kommer det att vidarebefordras till <code>jmsMessageReceiver</code>-instansen som då måste vara trådsäker.</p>
<p>För mer information om Spring JMS kolla in den <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jms.html" target="_blank">officiella dokumentationen</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring JDBC]]></title>
<link>http://cygni.wordpress.com/?p=211</link>
<pubDate>Tue, 19 Aug 2008 13:25:04 +0000</pubDate>
<dc:creator>Tommy Wassgren</dc:creator>
<guid>http://cygni.wordpress.com/?p=211</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och kommer att behandla hur man kan jobba med Jdb]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och kommer att behandla hur man kan jobba med <code>JdbcTemplate</code> och andra centrala klasser i modulen spring-jdbc.</p>
<p><!--more--></p>
<h2>Templating</h2>
<p>Ett designmönster som används flitigt i Spring är "template method". En template-metod definierar ett skelett för en algoritm. Algoritmen är abstrakt och det är upp till subklasser att definiera det konkreta beteendet för algoritmen. Nedanstående exempel som är kraftigt influerat från <a href="http://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">wikipedia</a> visar hur mönstret fungerar:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">/** A game that can be played... */
public interface Game {
    void initializeGame();
    void makePlay(int player);
    boolean endOfGame();
    void printWinner();
} 

/** Concrete implementation of the chess game... */
public class Chess implements Game {
    public void initializeGame() {
        // do chess stuff...
    } 

    public void makePlay(int player) {
        // do chess stuff...
    } 

    public boolean endOfGame() {
        // do chess stuff...
        return false;
    } 

    public void printWinner() {
        // do chess stuff...
    }
} 

/** Concrete implementation of the monopoly game... */
public class Monopoly implements Game {
    public void initializeGame() {
        // do monopoly stuff...
    } 

    public void makePlay(int player) {
        // do monopoly stuff...
    } 

    public boolean endOfGame() {
        // do monopoly stuff...
        return false;
    } 

    public void printWinner() {
        // do monopoly stuff...
    }
} 

/** The class containing the template method. */
public class GameTemplate {
    /**
     * This is a template method that plays the provided
     * game using a specified algorithm (initialize,
     * play, end, print winner)
     *
     * The template method is common to several games in
     * which players play against the others, but only one
     * player is playing at a given time.
     */
    public void play(int playersCount, Game game) {
        game.initializeGame(); 

        int j = 0;
        while (!game.endOfGame()){
            game.makePlay(j);
            j = (j + 1) % playersCount;
        } 

        game.printWinner();
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Template method</em></strong></td>
</tr>
</tbody>
</table>
<p>Exemplet ovan visar hur en algoritm appliceras på ett <code>Game</code>-objekt i metoden <code>play</code>. Exemplet är en aning förändrat jämfört med originalet så till vida att klassen <code>GameTemplate</code> inte är ett <code>Game</code> utan endast innehåller själva algoritmen för att få en lösare koppling mellan algoritmen och de faktiska <code>Game</code>-objekten.</p>
<p>Nu när vi känner till designmönstret "template method" kan vi kika vidare på templaten som tillhandahålls av Spring för JDBC-relaterade operationer, nämligen <code>JdbcTemplate</code>.</p>
<h2>JdbcTemplate</h2>
<p>Klassen <code>JdbcTemplate</code> är kärnan i den modul som kallas spring-jdbc. Klasserna i denna modul används när access till databasen sker via JDBC snarare än via ett O/R-mappningsramverk såsom Hibernate.</p>
<p>Att använda rå JDBC kan medföra en hel del problem för utvecklaren där Connections, Statements, ResultSets måste stängas, exceptions måste fångas osv. Kod som är skriven för rå JDBC-användning är ofta väldigt utförlig (verbose) och leder lätt till fel (såsom att glömma att stänga ett statement). Springs <code>JdbcTemplate</code> hjälper utvecklaren med många delar av de uppgifter som krävs för att använda JDBC.</p>
<table border="1">
<tbody>
<tr>
<th>Task</th>
<th>Spring</th>
<th>You</th>
</tr>
<tr>
<td>Connection Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>SQL</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Statement Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>ResultSet Management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Row Data Retrieval</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Parameter Declaration</td>
<td></td>
<td>X</td>
</tr>
<tr>
<td>Parameter Setting</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Transaction Management</td>
<td>X</td>
<td></td>
</tr>
</tbody>
</table>
<p>Tabellen ovan visar de delar som <code>JdbcTemplate</code> hjälper dig med jämfört med att använda rå JDBC.</p>
<p>Nedanstående exempel visar vanlig användning av rå JDBC med en enkel parameteriserad SELECT och en mappning mellan ett <code>Person</code>-objekt och ett <code>ResultSet</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">private static final String PERSON_QUERY =
        "select first_name, last_name, phone_number "
        + "from person where last_name = ?"; 

public List getPersonList1() {
    List list = new ArrayList();
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(PERSON_QUERY);
        statement.setString(1, "Svensson");
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            Person person = new Person(
                rs.getString("first_name"),
                rs.getString("last_name"),
                rs.getString("phone_number"));
                list.add(person);
        }
        rs.close();
    } catch (SQLException e) {
        // handle exception somehow...
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // handle exception somehow...
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                // handle exception somehow...
            }
        }
    }

    return list;
}</pre>
</td>
</tr>
<tr>
<td><strong><em>Rå JDBC - getPersonList1</em></strong></td>
</tr>
</tbody>
</table>
<p>Exemplet kan förenklas avsevärt genom användning av <code>JdbcTemplate</code> vilket metoden <code>getPersonList2</code> i nedanstående exempel visar.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public List getPersonList2 () {
    RowMapper personMapper = new RowMapper() {
        // Maps a row to a Person
        public Object mapRow(
                ResultSet rs,
                int rowNum) throws SQLException {

            return new Person(
                rs.getString("first_name"),
                rs.getString("last_name"),
                rs.getString("phone_number"));
        }
    };

    return getJdbcTemplate().query(
        PERSON_QUERY, new Object[] {"Svensson"}, personMapper);
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med RowMapper - getPersonList2</em></strong></td>
</tr>
</tbody>
</table>
<p>Vi antar i exemplet ovan att man kan få tag på en <code>JdbcTemplate</code> via metoden <code>getJdbcTemplate()</code>.</p>
<p>Några saker värda att notera:</p>
<ul>
<li>Kod för att hantera connections, statements etc. saknas helt. Detta hanteras av <code>JdbcTemplate</code> som öppnar och stänger alla resurser.</li>
<li>Mappning mellan SQL-resultatet och affärsobjektet sker i en <code>RowMapper</code>. Detta är ett tydligt mönster och <code>RowMapper</code>-objektet kan återanvändas om det deklareras utanför metoden. Förutom <code>RowMapper</code> finns även andra sätt att mappa data och dessa kan återfinnas i Springdokumentationen.</li>
<li>Ingen felhantering krävs. Alla eventuella exceptions fångas av <code>JdbcTemplate</code> och konverteras sedan till Springs egna unchecked exceptions mha. <code>SQLExceptionTranslator</code>. Istället för att kasta ett checked exception med en kryptisk databasunik felkod kan tydliga exceptions såsom <code>BadSqlGrammarException</code> eller <code>OptimisticLockingFailureException</code> kastas. De databaser som supportas out-of-the-box är DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL och Sybase. Naturligtvis går det även att plugga in egna <code>SQLExceptionTranslators</code>.</li>
</ul>
<p>Det finns även några inbyggda <code>RowMappers</code>. Metoden <code>queryForInt</code> som exemplifieras nedan skapar en intern <code>RowMapper</code> där ett SQL-resultat mappas mot ett heltal.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public int countPeople() {
    return getJdbcTemplate().queryForInt(
            "select count(*) from person ");
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med queryForInt</em></strong></td>
</tr>
</tbody>
</table>
<p>I exemplen ovan har endast SELECT-frågor mot databasen ställts. Det finns även metoder för att utföra uppdateringar, se exemplet nedan för en enkel parameteriserad uppdatering:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">private static final String UPDATE_PERSON =
    "update person set phone_number = ?"
    + "where first_name = ? and last_name = ?";

public void updatePhoneNumber(
        String firstName, String lastName, String phoneNumber) {

    getJdbcTemplate().update(
            UPDATE_PERSON,
            new Object[] {phoneNumber, firstName, lastName});
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JdbcTemplate med update</em></strong></td>
</tr>
</tbody>
</table>
<p><code>JdbcTemplate</code> behöver endast konfigureras upp med en datakälla. Det finns några bekväma klasser att ärva från för att enkelt få tag på <code>JdbcTemplate</code>-objektet. Klassen <code>JdbcDaoSupport</code> kan användas för DAO-objekt medan klassen <code>AbstractTransactionalDataSourceSpringContextTests</code> fungerar bra för JUnit-tester. Nedanstående exempel visar detta.</p>
<p>Så här kan en DAO-klass se ut:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class MyDao extends JdbcDaoSupport {
    private static final String UPDATE_PERSON =
        "update person set phone_number = ? "
        + "where first_name = ? and last_name = ?";

    public void updatePhoneNumber (
            String firstName, String lastName, String phoneNumber) {

        getJdbcTemplate().update(
                UPDATE_PERSON,
                new Object[] {phoneNumber, firstName, lastName});
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>DAO som ärver JdbcDaoSupport</em></strong></td>
</tr>
</tbody>
</table>
<p>När en DAO konfigureras så måste en <code>DataSource</code> injectas, detta kan exempelvis ske via en JNDI-uppslagning:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="myDataSource"
  class="org.springframework.jndi.JndiObjectFactoryBean"&#62;

    &#60;property name="lookupOnStartup" value="false" /&#62;
    &#60;property name="proxyInterface" value="javax.sql.DataSource" /&#62;
    &#60;property name="resourceRef" value="true" /&#62;
    &#60;property name="jndiName" value="jdbc/myds" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>dataSourceContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>Själva DAO-objekten kan exempelvis deklareras i en egen fil som kan användas både för produktion och för test.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean id="myDao" class="se.cygni.sample.spring.template.jdbc.MyDao"&#62;
    &#60;property name="dataSource" ref="dataSource" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>daoContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>När applikationen ska konfigureras för test så kan en <code>DataSource</code> konfigureras utan JNDI-uppslagning:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;bean
  id="myDataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource" &#62;

    &#60;property name="driverClassName"
        value="oracle.jdbc.driver.OracleDriver" /&#62;
    &#60;property name="url" value="jdbc:oracle:thin:@host:port:schema" /&#62;
    &#60;property name="username" value="scott" /&#62;
    &#60;property name="password" value="tiger" /&#62;
&#60;/bean&#62;</pre>
</td>
</tr>
<tr>
<td><strong><em>testDataSourceContext.xml</em></strong></td>
</tr>
</tbody>
</table>
<p>Ett JUnit-test kan se ut enligt följande:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class MyDaoTest
        extends AbstractTransactionalDataSourceSpringContextTests {

    private MyDao dao;

    protected String[] getConfigLocations() {
        return new String[] {
                "testDataSourceContext.xml",
                "daoContext.xml"
        };
    }

    public void testDao() {
        dao.updatePhoneNumber("Johnny", "Puma", "555-555 5555");

        int count = getJdbcTemplate().queryForInt(
            "select count(*) from person "
            + "where first_name = 'Johnny' "
            + "and last_name = 'Puma' "
            + "and phone_number = '555-555 5555'");

        assertTrue(count == 1);
    }

    public void setMyDao(MyDao dao) {
        this.dao = dao;
    }
}</pre>
</td>
</tr>
<tr>
<td><strong><em>JUnit testfall</em></strong></td>
</tr>
</tbody>
</table>
<p>I testet ovan visas hur dels <code>MyDao</code> injectas i testklassen eftersom filen <code>daoContext.xml</code> anges som en config-location. Även filen <code>testDataSourceContext.xml</code> inkluderas vilket leder till att en <code>DataSource</code> finns tillgänglig och då injectas denna <code>DataSource</code> i basklassen <code>AbstractTransactionalDataSourceSpringContextTests</code> vilket leder till att metoden <code>getJdbcTemplate</code> blir tillgänglig i testfallet.</p>
<p>Det finns även stöd för Java 5 i Springs JDBC modul. Genom att ärva klassen <code>SimpleJdbcDaoSupport</code> istället för <code>JdbcDaoSupport</code> i din DAO kan Java 5 metoder användas via klassen <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html#jdbc-SimpleJdbcTemplate" target="_blank">SimpleJdbcTemplate</a>. Se exemplet nedan.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public List&#60;Person&#62; getPeople() {
    ParameterizedRowMapper&#60;Person&#62; rowMapper =
        new ParameterizedRowMapper&#60;Person&#62;() {
            public Person mapRow(ResultSet rs, int rowNum)
                    throws SQLException {

                return new Person(
                        rs.getString("first_name"),
                        rs.getString("last_name"),
                        rs.getString("phone_number"));
            }
    };

    return getSimpleJdbcTemplate().query(
            "select first_name, last_name, phone_number from person",
            rowMapper);
}</pre>
</td>
</tr>
<tr>
<td><strong><em>SimpleJdbcTemplate</em></strong></td>
</tr>
</tbody>
</table>
<p>För mer information om Spring och JDBC rekommenderas <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html" target="_blank">Springdokumentationen</a> och <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html" target="_blank">JavaDoc för JdbcTemplate</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test-Driving a SimpleFormController with Spring MVC]]></title>
<link>http://richardbarabe.wordpress.com/?p=3</link>
<pubDate>Thu, 14 Aug 2008 14:38:44 +0000</pubDate>
<dc:creator>baraber</dc:creator>
<guid>http://richardbarabe.wordpress.com/?p=3</guid>
<description><![CDATA[In this article, I will show how one can develop &#8220;test-first&#8221; using Spring-webMVC and sp]]></description>
<content:encoded><![CDATA[<p>In this article, I will show how one can develop "test-first" using Spring-webMVC and spring-test.  I therefore assume you know the basics of <a href="http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html">spring-mvc</a>.  My example will be around some Person management system.  First, assume we have a Person object :</p>
<pre>public class Person {
    private Long id;
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}</pre>
<p>And a service interface allowing basic <a href="http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete">CRUD</a> operations for a person :</p>
<pre>public interface PersonService {
    public List read(Person p);
    public void save(Person p);
    public void delete(Person p);
}</pre>
<p>We want a web interface that allow the user to save a new Person or to modify an existing person.  For this I'll use a <a href="http://static.springframework.org/spring/docs/2.5.x/api/index.html?org/springframework/web/portlet/mvc/SimpleFormController.html">SimpleFormController</a>. It will be responsible for presenting the form, calling the person's service <code>save(Person),</code> and forwarding the user to a success page (when the person has correctly been saved).</p>
<p>This controller will be configured in a context file like this :</p>
<pre>&#60;beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&#62;

    &#60;bean name="/editPerson" class="myProject.web.EditPersonController"&#62;
        &#60;property name="commandClass" value="myProject.Person"/&#62;
        &#60;property name="formView" value="personForm"/&#62;
        &#60;property name="successView" value="personSaved"/&#62;
    &#60;/bean&#62;

&#60;/beans&#62;</pre>
<p>To have our test being able to load a context, we'll use the jUnit's <a href="http://junit.sourceforge.net/javadoc/org/junit/runner/RunWith.html">@RunWith</a> annotation, and to make our test load our specific context we'll use the Spring's <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/ContextConfiguration.html">@ContextConfiguration </a> annotation.  For more details on Spring's test API, see the <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html#testcontext-framework">chapter 13</a> of the Spring framework documentation.</p>
<pre><strong>@RunWith(SpringJUnit4ClassRunner.class)</strong>
<strong>@ContextConfiguration(locations={"/myProject/EditPersonControllerTest-context.xml"})</strong>
public class EditPersonControllerTest {
    <strong>@Autowired</strong>
    <strong>EditPersonController controller;</strong>

    /**
     * Tests the creation of a new Person.
     **/
    @Test
    public void testCreate() {

    }
}</pre>
<p>The @Autowired annotation will do "by-type" bean injection.  This means that since our context contains a single bean of type myProject.web.EditPersonController, that bean (the one we named "/editPerson") will be injected in field "controller" at runtime, before the test methods are called.  But for now, the test just doesn't compile because we haven't created the EditPersonController class.  Let's create this controller :<br />
<code> </code></p>
<pre>import org.springframework.web.servlet.mvc.SimpleFormController;

public class EditPersonController extends SimpleFormController {
}</pre>
<p>It does nothing for the moment, except allowing the test to compile.<br />
To test this newly created controller, we need a HttpServletRequest and a HttpServletResponse object.  These objects will be passed to the controller's handleRequest method.  Our test is, of course, not using a servlet engine that is able to create these objects for us, so we have to mock them.  Here comes the use of the Spring's <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/mock/web/MockHttpServletRequest.html">MockHttpServletRequest</a> and <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/mock/web/MockHttpServletResponse.html">MockHttpServletResponse</a> classes.  With these objects, we can easily simulate a HTTP request that will be forwarded to our controller.  We can then verify if a "GET" HTTP call will make our controller send the person form :</p>
<pre>/**
 * Tests the creation of a new Person.
 **/
@Test
public void testCreate() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
    assertEquals(controller.getFormView(), mv.getViewName());
}</pre>
<p>The <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/portlet/ModelAndView.html">ModelAndView</a> object is used to determine which view the controller chose to send to the user.<br />
Instead of doing :<br />
<em><code>assertEquals(controller.getFormView(), mv.getViewName());</code></em><br />
We could have done :<br />
<em><code> import static org.springframework.test.web.ModelAndViewAssert.*;<br />
[...]<br />
assertViewName(mv, controller.getFormView());<br />
</code><code>[...]</code></em></p>
<p>Now the user is provided a form with two input fields.  One for the "firstname" and one for the "lastname".  He fills those fields and submit the form.  The controller is then called with the "fistname" and "lastname" posted by the user.  It must normally save the person and return the "successView" which we named "personSaved" (see the XML context defined previously).  Let's now add this behavior to our test :</p>
<pre><strong>import static org.springframework.test.web.ModelAndViewAssert.*;</strong>

...

/**
 * Tests the creation of a new Person.
 **/
@Test
public void testCreate() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
    assertEquals(controller.getFormView(), mv.getViewName());

    <strong>request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setParameter("firstName", "Richard");
    request.setParameter("lastname", "Barabé");
    mv = controller.handleRequest(request, new MockHttpServletResponse());
    assertViewName(mv, controller.getSuccessView());</strong>
}</pre>
<p>So far we've tested that while creating a new Person, the user first asks the Person form (with an HTTP GET call), then submits that form (with an HTTP POST call that details person's information) and is redirected to a success page when finished.  We can say we tested the navigation part of the "create new Person" use case.</p>
<p>But, did the controller really saved the Person ? In other words : Did the controller called the PersonService's <code>save(Person p)</code> method ?  To test this, I will use <a href="http://www.easymock.org/">EasyMock</a> to mock a PersonService, tell EasyMock I want this PersonService's <code>save(Person p)</code> method to be called once with the correct person, and then I will pass that PersonService mock to the controller.  Once done, my test will know if the controller really called the PersonService adequately. Here is the code of the test :</p>
<p><code> </code></p>
<pre><strong>import static org.easymock.EasyMock.*;</strong>

...

/**
 * Tests the creation of a new Person.
 **/
@Test
public void testCreate() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
    assertEquals("personForm", mv.getViewName());

    request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setParameter("firstName", "Richard");
    request.setParameter("lastname", "Barabé");
    <strong>
    // Create the service's imitation
    PersonService serviceMock = createMock(PersonService.class);
    controller.setPersonService(serviceMock);
    // The save method should be called with "Richard Barabé"
    serviceMock.save(new Person("Richard", "Barabé"));
    // The save method should be called only once
    expectLastCall().once();
    // Finished telling easymock how my service should be used.
    replay(serviceMock);
    </strong>

    mv = controller.handleRequest(request, new MockHttpServletResponse());
    assertViewName(mv, "personSaved");
    <strong>
    // Verify that the service have been used as we expect
    // (method save called once with "Richard Barabé")
    verify(serviceMock);
    </strong>
}</pre>
<p>For this to compile, I need to add a PersonService field and its getter/setter in the controller :<br />
<code> </code></p>
<pre>import org.springframework.web.servlet.mvc.SimpleFormController;
import myProject.PersonService;
public class EditPersonController extends SimpleFormController {
    <strong>private PersonService service;

    public void setPersonService(PersonService service) {
        this.service = service
    }

    public PersonService getPersonService() {
        return this.service;
    }</strong>
}</pre>
<p>Now the test asserts the service has been called correctly.  As we run it, we can see it fails with the following message :<br />
<code> </code></p>
<pre>java.lang.AssertionError:
  Expectation failure on verify:
    save(myProject.Person@1f2cea2): expected: 1, actual: 0
	at org.easymock.internal.MocksControl.verify(MocksControl.java:82)
	at org.easymock.EasyMock.verify(EasyMock.java:1410)
        ...</pre>
<p>This just means our controller didn't call the service's save method as expected.  Let's make our controller do it's job by adding the expected call :</p>
<p><code> </code></p>
<pre>import org.springframework.web.servlet.mvc.SimpleFormController;
import myProject.PersonService;
public class EditPersonController extends SimpleFormController {
    private PersonService service;

    <strong>protected doSubmitAction(Object o) {
        this.service.save((Person) o)
    }</strong>

    public void setPersonService(PersonService service) {
        this.service = service
    }

    public PersonService getPersonService() {
        return this.service;
    }
}</pre>
<p>Running the test now should succeed.  But, unfortunately, the bar is red again.  For time consideration, I'll leave aside the investigation and go right to the solution : we did not override the equals and hashcode methods of the Person class.  Our controller that received the form submission did create a new Person, setting its first and last name.  It then passed this new object to the doFormSubmitAction(Object) that called our mock passing the new person.  But we told EasyMock we expected our service to be called with another Person object.  Default implementation of the equals method in object makes the following statement <strong>false</strong> :<br />
<em> (new Person("Richard","Barabé")).equals(new Person("Richard","Barabé"))</em><br />
So let's implement those hashCode and equals methods (I use Eclipse to generate this "boiler plate" code) :</p>
<pre>public class Person {
    private Long id;
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    <strong>@Override
    public int hashCode() {
    	final int prime = 31;
    	int result = 1;
    	result = prime * result
    	        + ((firstName == null) ? 0 : firstName.hashCode());
    	result = prime * result
    	        + ((lastName == null) ? 0 : lastName.hashCode());
    	return result;
    }

    @Override
    public boolean equals(Object obj) {
    	if (this == obj)
    	    return true;
    	if (obj == null)
    	    return false;
    	if (getClass() != obj.getClass())
    	    return false;
    	final Person other = (Person) obj;
    	if (firstName == null) {
    	    if (other.firstName != null)
    	        return false;
    	} else if (!firstName.equals(other.firstName))
    	    return false;
    	if (lastName == null) {
    	    if (other.lastName != null)
    	        return false;
    	} else if (!lastName.equals(other.lastName))
    	    return false;
        return true;
    }</strong>
}</pre>
<p>Now the code behaves correctly when we have two persons with the same fistName and lastName.  And that green bar is back again.</p>
<p>There we are, we have successfully developped and tested our controller.  This article is to be continued, and next time we'll go over the Validator  and View implementation.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Terracotta &amp; SpringSource Application Platform]]></title>
<link>http://cygni.wordpress.com/?p=239</link>
<pubDate>Fri, 08 Aug 2008 13:21:02 +0000</pubDate>
<dc:creator>Henrik Lundgren</dc:creator>
<guid>http://cygni.wordpress.com/?p=239</guid>
<description><![CDATA[I thought I would share this with the rest of the world and maybe save humanity a few hours of trial]]></description>
<content:encoded><![CDATA[<p>I thought I would share this with the rest of the world and maybe save humanity a few hours of trial and error. I have managed to make Terracotta play along with SpringSource Application Platform (S2AP).</p>
<p>There are three things that needs to be done: first we need to start up S2AP with Terracotta enabled, then we need to make Terracotta classes visible to OSGi bundles and finally we have to baptize the class loader in your bundle so that Terracotta can properly identify your clustered objects.</p>
<p>I assume that both Terracotta 2.6.2 and SpringSource Application Platform RC-1 is installed.</p>
<h2>Wrap the Startup Script</h2>
<p>In order to enable Terracotta in the platform we need to start the JVM with some additional arguments. The easiest way is to wrap the start up script with another script that set the JAVA_OPTS variable. I created a script called startup-dso.bat in %PLATFORM_HOME%/bin:<br />
<code><br />
setlocal<br />
set TC_INSTALL_DIR=&#60;path_to_local_Terracotta_home&#62;<br />
set TC_CONFIG_PATH=&#60;path\to\tc-config.xml&#62;<br />
call %TC_INSTALL_DIR%\bin\dso-env.bat -q<br />
set JAVA_OPTS=%TC_JAVA_OPTS%<br />
call startup.bat<br />
endlocal<br />
</code><br />
Remember to generate a Terracotta boot jar for you environment.</p>
<p>If you run the script it will look promising until you see java.lang.ClassNotFoundException: com.tc.object.bytecode.Manageable in the console. This is because the OSGi bundle class loader cannot see the Terracotta classes that are loaded by the boot class loader.</p>
<h2>Delegate Loading of Terracotta Classes</h2>
<p>We need to tell the OSGi container in S2AP to delegate the loading of Terracotta classes to the boot class loader. This is achieved by modifying the java5-platform.profile or java6-platform.profile (as appropriate for the level of Java which you're using) found in the platform's lib directory and adding Terracotta's packages (com.tc.*) to the list under the org.osgi.framework.bootdelegation key.</p>
<h2>Naming class loaders</h2>
<p>Now only one more thing remains to do: the class loader for the bundle that contains the objects you want to cluster needs to be named and registered:</p>
<p><code><br />
static {<br />
NamedClassLoader ncl = (NamedClassLoader) myClass.getClassLoader();<br />
ncl.__tc_setClassLoaderName("bundle_name");<br />
ClassProcessorHelper.registerGlobalLoader(ncl);<br />
}<br />
</code></p>
<p>The code above have to be run when your bundle is loaded, I just added it to the Spring managed bean that i wanted to cluster. This is a hack as you introduce compile time dependencies to Terracotta and you can only cluster objects from bundles that you can modify. But we will have to do with this until Terracotta get better support for OSGi.</p>
<p>Add the terracotta boot jar to you build path to satisfy the compile time dependency. Make sure that your ordinary runtime classpath doesn't contain the boot jar.</p>
<p>Thats it!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring Documentation 2 For Example Springドキュメント２　例]]></title>
<link>http://takechan.wordpress.com/?p=88</link>
<pubDate>Sat, 19 Jul 2008 03:01:38 +0000</pubDate>
<dc:creator>Take chan</dc:creator>
<guid>http://takechan.wordpress.com/?p=88</guid>
<description><![CDATA[As I was experimenting Spring HTTP Invoker with http://marxsoftware.blogspot.com/2008/07/simple-spri]]></description>
<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0;"><span style="font-size:small;font-family:Times New Roman;">As I was experimenting Spring HTTP Invoker with </span><a href="http://marxsoftware.blogspot.com/2008/07/simple-spring-http-remoting-example.html"><span style="font-size:small;font-family:Times New Roman;">http://marxsoftware.blogspot.com/2008/07/simple-spring-http-remoting-example.html</span></a><span style="font-size:small;font-family:Times New Roman;">, I was also referring to Spring documentation. I had one question about using SimpleUrlHandlerMapping<span>  </span>in the example; I could not find any description about it within HTTP Invoker section. (It was discussed in MVC Controller section.) So, I tried to run the example without it; I got an exception error (of course). If I don’t have any example and have only Spring documentation, I would never make it run by myself.</span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-size:small;font-family:Times New Roman;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-size:small;"><span style="font-family:Times New Roman;">Spring HTTP Invoker</span><span style="font-family:&#34;" lang="JA">の実験を</span></span><a href="http://marxsoftware.blogspot.com/2008/07/simple-spring-http-remoting-example.html"><span style="font-size:small;font-family:Times New Roman;">http://marxsoftware.blogspot.com/2008/07/simple-spring-http-remoting-example.html</span></a><span style="font-size:small;"><span style="font-family:&#34;" lang="JA">でしていたとき、</span><span style="font-family:Times New Roman;">Spring</span><span style="font-family:&#34;" lang="JA">のドキュメントも見ていました。</span><span style="font-family:Times New Roman;">SimpleUrlHandlerMapping</span><span style="font-family:&#34;" lang="JA">というものが例の中でつかわれておりそれに疑問をもちましたが、</span><span style="font-family:Times New Roman;">Spring</span><span style="font-family:&#34;" lang="JA">のドキュメントには</span><span style="font-family:Times New Roman;">HTTP Invoker</span><span style="font-family:&#34;" lang="JA">のところでは、何もかかれていません。（</span><span style="font-family:Times New Roman;">MVC Controller</span><span style="font-family:&#34;" lang="JA">でかかれていた。）ためしに、その定義をなくして、例を動かすと、（もちろん）エラーとなる。もし、例がなく、</span><span style="font-family:Times New Roman;">Spring</span><span style="font-family:&#34;" lang="JA">のドキュメントだけだったら、自分ひとりで、</span><span style="font-family:Times New Roman;">HTTP</span><span style="font-family:&#34;" lang="JA">　</span><span style="font-family:Times New Roman;">Invoker</span><span style="font-family:&#34;" lang="JA">を動かすことはできなかったに違いない。</span></span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring Documentation　Springドキュメント]]></title>
<link>http://takechan.wordpress.com/?p=86</link>
<pubDate>Fri, 18 Jul 2008 02:46:38 +0000</pubDate>
<dc:creator>Take chan</dc:creator>
<guid>http://takechan.wordpress.com/?p=86</guid>
<description><![CDATA[Spring is a nice framework, but there is one thing I don’t like. It is difficult for me to try thi]]></description>
<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0;"><span style="font-size:small;font-family:Times New Roman;">Spring is a nice framework, but there is one thing I don’t like. It is difficult for me to try things written in its documentation. One major reason is that there are none of complete examples. There are so many code examples, but most of them are not completed or missing something dependency. This would be okay if readers understand basic things, but that assumption is not acceptable. They should provide a complete example besides those incomplete examples. </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-size:small;font-family:Times New Roman;"> </span></p>
<p class="MsoNormal" style="margin:0;"><span style="font-size:small;"><span style="font-family:Times New Roman;">Spring</span><span style="font-family:&#34;" lang="JA">はすばらしいフレームワークだけれど、きらいなところがひとつ。ドキュメントに書かれてあることを使ってみようとすることが難しい。ひとつの理由は、全く完全に書かれた例がない。（すこしはあるかも？）たくさんのコードの例がでてくるけど、たいていは完全ではないか、何かが、書かれていない。読者がすでに基本的なことを知っている場合はいいけれど。しかしこの前提は間違っている。完全な例を常につけておくべきだと思う。</span></span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Is single vendor-driven open source a greater security risk?]]></title>
<link>http://saviorodrigues.wordpress.com/?p=350</link>
<pubDate>Wed, 16 Jul 2008 13:00:40 +0000</pubDate>
<dc:creator>Savio Rodrigues</dc:creator>
<guid>http://saviorodrigues.wordpress.com/?p=350</guid>
<description><![CDATA[Ounce Labs, a software risk analysis company, has uncovered two security vulnerabilities in the Spri]]></description>
<content:encoded><![CDATA[<p><a href="http://www.ouncelabs.com/">Ounce Labs</a>, a software risk analysis company, has uncovered two security vulnerabilities in the <a href="http://www.springframework.org/" target="_blank">Spring Framework</a>.</p>
<p>Considering how long Spring has been in use, and its popularity, how could such vulnerabilities remain hidden so long? After all, isn't one of the hallmarks of open source the strong community vetting? Could it be that the shift towards single vendor-driven open source is making open source riskier?</p>
<p><strong>What the Spring vulnerabilities are</strong></p>
<p>Kudos to Ryan Berg, chief scientist and co-founder of Ounce Labs, and Ounce team for uncovering the issues and working with SpringSource to raise awareness.</p>
<p>According to Ounce Labs:</p>
<blockquote><p>The specific vulnerabilities are "ModelView Injection" and "Data Submission to Non-Editable Fields." These vulnerabilities allow attackers to subvert the expected application logic and behavior, gaining control of the application itself, and access to any data, credentials or keys held in the application.</p></blockquote>
<p>If your applications use the Spring Framework, be sure to read <a href="http://www.springsource.com/securityadvisory">FAQs from the SpringSource advisory</a> and the <a href="www.ouncelabs.com/springmvc">Ounce Security Advisory</a>.</p>
<p><strong>The deeper question on open source vetting</strong></p>
<p>Now, the reason this story caught my eye:</p>
<blockquote><p>"As we put more and more trust into the frameworks that are the foundation of our applications, we need to make sure we understand the security decisions made so we can make the right implementation choices."</p></blockquote>
<p>Two key benefits of OSS are the ability to read and understand the code we use and that "many eyes scouring the code" makes the product more secure.</p>
<p>Considering the millions of downloads of the Spring Framework, should we have expected someone to discover these security holes earlier? Or do developers use what the next guy/gal is using, trusting that "someone" has done the due diligence?</p>
<p>How should we interpret the news versus the long-held belief of increased security as a result of "more eyes scouring the code"? Could that be a trait of merit-based OSS projects that isn't likely to show up in OSS projects where a single vendor writes the code?</p>
<p>If developers outside the company can't contribute code, what is the likelihood that a developer will look at a piece of code within the project and ask, "How can I make this better?" -- and in the process uncover a potential security issue?</p>
<p>I'm really asking a fundamental question: Are merit-based OSS projects more secure than single-vendor-driven OSS projects?</p>
<p>Thoughts?</p>
<p><em>PS: I <a href="http://weblog.infoworld.com/openresource/archives/2007/08/disclaimer_expl.html">should </a>state: "The postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions."</em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[test categories]]></title>
<link>http://xenzero.wordpress.com/?p=3</link>
<pubDate>Tue, 08 Jul 2008 10:51:02 +0000</pubDate>
<dc:creator>xenzero</dc:creator>
<guid>http://xenzero.wordpress.com/?p=3</guid>
<description><![CDATA[test categoriestest categoriestest categoriestest categories
]]></description>
<content:encoded><![CDATA[<p>test categoriestest categoriestest categoriestest categories</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring Framework Overview]]></title>
<link>http://lequangminh04.wordpress.com/?p=4</link>
<pubDate>Tue, 24 Jun 2008 10:17:32 +0000</pubDate>
<dc:creator>lequangminh04</dc:creator>
<guid>http://lequangminh04.wordpress.com/?p=4</guid>
<description><![CDATA[1.  What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (a]]></description>
<content:encoded><![CDATA[<p class="que" align="justify"><strong><span class="queIndex">1.</span>  What is IOC (or Dependency Injection)?</strong></p>
<div class="medlist"><span class="queIndex">The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.</span></div>
<div><span class="queIndex">i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.</span></div>
<p> </p>
<div><strong><span class="queIndex">2. </span>What are the different types of IOC (dependency injection) ?</strong></div>
<p> </p>
<p class="medlist" align="justify"><span class="queIndex">There are three types of dependency injection: </span></p>
<ul>
<li><strong>Constructor Injection</strong> (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.</li>
<li><strong>Setter Injection</strong> (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).</li>
<li><strong>Interface Injection </strong>(e.g. Avalon): Injection is done through an interface. <em>Note: Spring supports only Constructor and Setter Injection</em></li>
</ul>
<p> </p>
<p> </p>
<p class="que" align="justify"><strong><span class="queIndex">3. </span>What are the benefits of IOC (Dependency Injection)?</strong></p>
<p class="medlist" align="justify">Benefits of IOC (Dependency Injection) are as follows:</p>
<ul>
<li>
<p class="medlist" align="justify">Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.</p>
</li>
<li>
<p class="medlist" align="justify">Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.</p>
</li>
<li>
<p class="medlist" align="justify">Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.</p>
</li>
<li>
<p class="medlist" align="justify">IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.</p>
</li>
</ul>
<p> </p>
<p class="que" align="justify"><strong><span class="queIndex">4. </span> What is Spring ?</strong></p>
<p class="medlist" align="justify">Spring is an <a id="KonaLink0" class="kLink" href="http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#" target="_top"><span style="font-weight:400;font-size:13px;color:#f26522;position:static;"><span class="kLink" style="font-weight:400;font-size:13px;color:#f26522;font-family:'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif;position:relative;">open </span><span class="kLink" style="font-weight:400;font-size:13px;color:#f26522;font-family:'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif;position:relative;">source</span></span></a> framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.</p>
<p class="que" align="justify"><strong><span class="queIndex">5. </span>What are the advantages of Spring framework?</strong></p>
<p class="medlist" align="justify">The advantages of Spring are as follows:</p>
<ul>
<li>Spring has layered architecture. Use what you need and leave you don't need now.</li>
<li>Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.</li>
<li>Dependency Injection and Inversion of Control Simplifies JDBC</li>
<li>Open source and no vendor lock-in.</li>
</ul>
<p> </p>
<p class="que" align="justify"><strong><span class="queIndex">6. </span>What are features of Spring ?</strong></p>
<ul>
<li>
<div class="navlink">Lightweight:</div>
<p class="medlist" align="justify">spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.</p>
</li>
<li>
<div class="navlink">Inversion of control (IOC):</div>
<p class="medlist" align="justify">Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.</p>
</li>
<li>
<div class="navlink">Aspect oriented (AOP):</div>
<p class="medlist" align="justify">Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.</p>
</li>
<li>
<div class="navlink">Container:</div>
<p class="medlist" align="justify">Spring contains and manages the life cycle and configuration of application objects.</p>
</li>
<li>
<div class="navlink">MVC Framework:</div>
<p class="medlist" align="justify">Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view <a id="KonaLink1" class="kLink" href="http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#" target="_top"><span style="font-weight:400;font-size:13px;color:#f26522;position:static;"><span class="kLink" style="font-weight:400;font-size:13px;color:#f26522;border-bottom:#f26522 1px solid;font-family:'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif;position:relative;background-color:transparent;">technologies</span></span></a> like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.</p>
</li>
<li>
<div class="navlink">Transaction Management:</div>
<p class="medlist" align="justify">Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.</p>
</li>
<li>
<div class="navlink">JDBC Exception Handling:</div>
<p class="medlist" align="justify">The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS</p>
</li>
</ul>
<p> </p>
<p class="que" align="justify"><strong><span class="queIndex">7. </span>How many modules are there in Spring? What are they?</strong></p>
<p class="medlist" align="justify">      Spring comprises of seven modules. They are..</p>
<ul>
<li>
<div class="navlink">The core container:</div>
<p>The core container provides the essential functionality of the Spring framework. A primary component of the core container is the <code>BeanFactory</code>, an implementation of the Factory pattern. The <code>BeanFactory</code> applies the <em>Inversion of Control</em> (IOC) pattern to separate an application's configuration and dependency specification from the actual application code. </li>
<li>
<div class="navlink">Spring context:</div>
<p>The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. </li>
<li>
<div class="navlink">Spring AOP:</div>
<p>The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. </li>
<li>
<div class="navlink">Spring DAO:</div>
<p>The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different <a id="KonaLink2" class="kLink" href="http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#" target="_top"><span style="font-weight:400;font-size:13px;color:#f26522;position:static;"><span class="kLink" style="font-weight:400;font-size:13px;color:#f26522;font-family:'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif;position:relative;">database</span></span></a> vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy. </li>
<li>
<div class="navlink">Spring ORM:</div>
<p>The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis <a id="KonaLink3" class="kLink" href="http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#" target="_top"><span style="font-weight:400;font-size:13px;color:#f26522;position:static;"><span class="kLink" style="font-weight:400;font-size:13px;color:#f26522;border-bottom:#f26522 1px solid;font-family:'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif;position:relative;background-color:transparent;">SQL</span></span></a> Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies. </li>
<li>
<div class="navlink">Spring Web module:</div>
<p>The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. </li>
<li>
<div class="navlink">Spring MVC framework:</div>
<p>The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. </li>
</ul>
<p class="que" align="justify"><strong><span class="queIndex">8. </span>What are the types of Dependency Injection Spring supports ?</strong></p>
<ul>
<li>
<div class="navlink">Setter Injection:</div>
<p>Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.</li>
<li>
<div class="navlink">Constructor Injection:</div>
<p>Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborato</li>
</ul>
<p class="que" align="justify"><strong><span class="queIndex">9. </span>What is Bean Factory ?</strong></p>
<p class="medlist" align="justify">A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.</p>
<ul>
<li>BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.</li>
<li>BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.</li>
</ul>
<p class="que" align="justify"><strong><span class="queIndex">10. </span>What is Application Context?</strong></p>
<p class="medlist" align="justify">A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:</p>
<ul>
<li>A means for resolving text messages, including support for internationalization.</li>
<li>A generic way to load file resources.</li>
<li>Events to beans that are registered as listeners.</li>
</ul>
<p class="que" align="justify"><strong><span class="queIndex">11. </span>What is the difference between Bean Factory and Application Context ?</strong>  </p>
<p class="medlist" align="justify">On the surface, an application context is same as a bean factory. But application context offers much more..</p>
<ul>
<li>Application contexts provide a means for resolving text messages, including support for i18n of those messages. </li>
<li>Application contexts provide a generic way to load file resources, such as images. </li>
<li>Application contexts can publish events to beans that are registered as listeners. </li>
<li>Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. </li>
<li>ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. </li>
<li>MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable </li>
</ul>
<p> </p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring - Konfiguration via annotations]]></title>
<link>http://stacktrace.se/?p=217</link>
<pubDate>Mon, 16 Jun 2008 14:25:50 +0000</pubDate>
<dc:creator>Tommy Wassgren</dc:creator>
<guid>http://stacktrace.se/?p=217</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och kommer att förklara hur Spring kan konfigure]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och kommer att förklara hur Spring kan konfigureras mha av annotations. Detta är sista delen i denna artikelserie innan vi tar sommaruppehåll men vi ser fram emot fler artiklar till hösten.</p>
<p>Konfiguration av en springapplikation brukar oftast ske mha XML-context som visats i ett antal exempel tidigare i denna serie, bland annat i artikeln om <a href="http://stacktrace.se/2008/06/09/spring-som-di-ramverk-sfb/">Spring som DI-ramverk</a>. Det finns dock andra möjligheter att konfigurera upp din Spring-applikation. Ett sätt är att använda annotations.</p>
<p><!--more--></p>
<p>Det finns en serie annotations som kan användas när en applikation ska sättas ihop via annotations. Den annotation som enkelt hanterar <a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> (DI) kallas <code>@Autowired</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">@Autowired
public void setPersonDao(PersonDao personDao) {
    this.personDao = personDao;
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<p>Ovanstående exempel visar hur ett objekt av typen <code>PersonDao</code> kommer att injectas till metoden <code>setPersonDao</code>. Objektet av typen <code>PersonDao</code> måste vara känt av Spring och måste alltså vara skapat i ett spring-context (via ex XML eller annotations).</p>
<p>För att hitta de komponenter som ska skapas och injectas som i exemplet ovan kan man antingen använda vanliga XML-context eller använda "classpath scanning". Classpath scanning startas via en springkomponent som scannar av classpathen efter lämpliga klasser att instansiera. De komponenter som eftersöks är markerade via annotations med en stereotyp. De stereotyper som finns från och med Spring 2.5 är <code>@Component</code>, <code>@Repository</code>, <code>@Service</code> och <code>@Controller</code>. <code>@Component</code> är en generell stereotyp som kan sättas på vilken springhanterad komponent som helst. De övriga stereotyperna är specialiseringar av komponenter. Om du vet vilken typ av komponent det är du annoterar (dvs en tjänst, data access, MVC controller) bör du använda den specialiserade annotationen, detta är dock bara en markering och medför i dagsläget ingen ytterligare programmatisk signifikans. För att starta scanningen av classpathen måste en komponent deklareras i ex ett XML-kontext enligt exemplet nedan.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">&#60;?xml version="1.0" encoding="UTF-8"?&#62;
&#60;beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd"&#62;

  &#60;context:component-scan
    base-package="se.cygni.sample.spring.annotation"/&#62;
&#60;/beans&#62;</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<p>Om ovanstående komponent deklareras och kommer alla klasser i paketet <code>se.cygni.sample.spring.annotation</code> att scannas efter stereotypannoteringar, skapas och kopplas ihop. Detta innebär alltså att alla klasser som har annotationerna <code>@Component</code>, <code>@Service</code>, <code>@Repository</code> eller <code>@Controller</code> kommer att bli skapade i springcontainern.</p>
<p>Nedanstående exempel visar hur en tjänst (<code>PersonService</code>) kopplas ihop med en DAO (DAO = Data Access Object) via annoteringar.</p>
<p>Antag nedanstående tjänstegränssnitt och DAO-gränssnitt. DAO-gränssnittet erbjuder klassiska CRUD-metoder och persontjänsten är lite intelligentare.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public interface PersonService {
    Person save(Person person);
    Person get(int id);
    List getAll();
    void delete(int id);
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public interface PersonDao {
    Person create(Person person);
    Person retrieve(int id);
    List retrieveAll();
    Person update(Person person);
    boolean delete(int id);
    boolean exists(int id);
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<p>De objekt som kan hanteras av persontjänsten är av typen <code>Person</code> och ser ut så här:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">public class Person {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

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

    public String getName() {
        return name;
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<p>Ok, när gränssnitten är färdigdefinierade kan vi tillhandahålla implementationer av dessa. Implementationerna innehåller de stereotypannotationer som krävs för att Spring ska kunna skapa upp dessa och koppla ihop objekten via <code>@Autowired</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">@Service("myPersonService")
public class PersonServiceImpl implements PersonService {
    private PersonDao personDao;

    public void delete(int id) {
        personDao.delete(id);
    }

    public Person get(int id) {
        if (personDao.exists(id)) {
            return personDao.retrieve(id);
        } else {
            return null;
        }
    }

    public List getAll() {
        return personDao.retrieveAll();
    }

    public Person save(Person person) {
        if (personDao.exists(person.getId())) {
            return personDao.update(person);
        } else {
            return personDao.create(person);
        }
    }

    @Autowired
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre style="font-size:8pt;">@Repository("myPersonDao")
public class InMemoryPersonDao implements PersonDao {
    private int idCounter;
    private Map repository = new HashMap();

    public Person create(Person person) {
        idCounter++;
        person.setId(idCounter);
        repository.put(Integer.valueOf(idCounter), person);
        return person;
    }

    public Person retrieve(int id) {
        Person person = repository.get(Integer.valueOf(id));
        if (person == null) {
            throw new IllegalStateException("Person " + id + " does not exist");
        }
        return person;
    }

    public List retrieveAll() {
        return new ArrayList(repository.values());
    }

    public Person update(Person personToUpdate) {
        Integer id = Integer.valueOf(personToUpdate.getId());
        Person person = repository.get(id);
        if (person == null) {
            throw new IllegalStateException("Person " + id + " does not exist");
        }
        repository.put(id, personToUpdate);
        return personToUpdate;
    }

    public boolean delete(int id) {
        Person deleted = repository.remove(Integer.valueOf(id));
        return deleted != null;
    }

    public boolean exists(int id) {
        return repository.containsKey(Integer.valueOf(id));
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>&#160;</td>
</tr>
</table>
<p>Ovanstående skapar alltså två objekt. Notera att klasserna är annoterade med <code>@Service</code> respektive <code>@Repository</code>. Det ena objektet är av typen <code>PersonServiceImpl</code> och är namngivet till <code>myPersonService</code>. Man måste inte namnge de komponenter som skapas utan kan endast skriva ex <code>@Service</code> istället för <code>@Service("namn")</code>. Defaultnamnet på en komponent följer Springs namnstandard på beans så objektet ovan skulle alltså heta <code>personServiceImpl</code>. Metoden <code>setPersonDao</code> använder <code>@Autowired</code> och kommer alltså att kopplas ihop med en instans av typen <code>PersonDao</code> och den enda instansen heter i ovanstående exempel <code>myPersonDao</code>. Bindning av komponenter sker alltså "by type" och inte "by name". Namnen kan dock användas om man programmatiskt använder en bean factory för att hämta beans eller om man vill injecta och referera någon namngiven bean ifrån ett XML-context. Dock kan man specificera tydligare vilka objekt som ska kopplas ihop via användning av Qualifiers men det kommer jag inte att behandla i detta inlägg.</p>
<h2>Övriga annoteringar</h2>
<p>Spring tillhandahåller ytterligare annoteringar för att konfigurera springapplikationer.</p>
<ul>
<li><code>@Required</code><br />
Används på metoder som måste injectas. Detta hanteras via en post processor som helt enkelt avbryter exekvering ifall metoden inte blivit anropad. Läs mer <a href="http://static.springframework.org/spring/docs/2.5.x/reference/metadata.html#metadata-annotations-required" target="_blank">här</a></li>
<li><code>@Resource</code>, <code>@PostConstruct</code> och <code>@PreDestroy</code><br />
Spring erbjuder stöd för JSR-250 annoteringar. <code>@PostConstruct</code> och <code>@PreDestroy</code> kan användas för <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lifecycle" target="_blank">lifecyclehantering</a> såsom interfacen InitializingBean och DisposableBean. @Resource används för dependency injection och kan även exekveras exempelvis i en J2EE-container med stöd för JEE 5.</li>
<li><code>@Transactional</code><br />
Används med Spring-TX för att markera transaktionsattribut direkt i en javaklass istället för i en separat XML-fil. Läs mer om <a href="http://static.springframework.org/spring/docs/2.5.x/reference/transaction.html#transaction-declarative-annotations" target="_blank">@Transactional</a> och <a href="http://static.springframework.org/spring/docs/2.5.x/reference/transaction.html" target="_blank">Spring-TX</a>.</li>
</ul>
<h2>Fördelar och nackdelar</h2>
<p>Fördelarna med att använda annotations för springkonfigurationen är uppenbara:</p>
<ul>
<li>Det blir knappt någon XML.</li>
<li>Stereotypning av komponenter ger en tydlig bild av komponentens syfte.</li>
<li>Det går snabbt att skapa en applikation som hanteras av spring utan bökig konfiguration.</li>
</ul>
<p>Nackdelarna:</p>
<ul>
<li>Det kan bli svårt att få överblick över applikationen och hur komponenterna kopplas ihop eftersom det hela blir lite "magiskt".</li>
<li>Det kan bli knöligt när komplexare ramverksklasser och liknande ska kopplas och då använder man typiskt en XML-fil i alla fall.</li>
</ul>
<p>Läs mer om konfiguration via annotations <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config" target="_blank">här</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring som DI-ramverk]]></title>
<link>http://cygni.wordpress.com/?p=210</link>
<pubDate>Mon, 09 Jun 2008 13:57:59 +0000</pubDate>
<dc:creator>Robert Burén</dc:creator>
<guid>http://cygni.wordpress.com/?p=210</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och kommer att förklara hur Spring kan användas]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och kommer att förklara hur Spring kan användas som DI-ramverk.</p>
<h2>Spring som DI-ramverk</h2>
<p>Spring är ett Dependency Injection-ramverk (se tidigare artikel gällande <a href="http://stacktrace.se/2008/05/30/dependendy_injection_d/">Dependency Injection</a>). Det är också så många andra saker, men i sin enklaste form är Spring ändå i första hand ett DI-ramverk.</p>
<p>Om du designar din applikation med hjälp av Dependency Injection kan du konfigurera Spring att hantera hur varje enskild komponent ska skapas, konfigureras och bindas ihop med övriga komponenter. En "komponent" i Spring är en vanlig POJO, komponenter som hanteras av Spring kallas för "Spring Beans" (eller på svenska "bönor") även om de inte nödvändigtvis måste uppfylla JavaBeans-specifikationen.</p>
<p><!--more--><br />
Det centrala objektet i Springs DI-hantering är en <code>BeanFactory</code>. En <code>BeanFactory</code> ansvarar bland annat för att skapa bönor, livscykelhantering och att binda ihop bönorna enligt den konfiguration du tillhandahåller. Det vanligaste sättet att konfigurera dina bönor är att använda XML-konfiguration men det finns även andra konfigurationssätt exempelvis via property-filer eller via annotations. En <code>BeanFactory</code> kan skapas manuellt, det vanligaste är dock att man skapar en <code>BeanFactory</code> via någon av det hjälpklasser som tillhandahålls av Spring exempelvis genom användning av <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-create">ContextServletListener</a> för webbapplikationer. En specialiserad form av <code>BeanFactory</code> är ett <code>ApplicationContext</code> som är det man typiskt använder, förklaringen till detta hittar du <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-introduction-ctx-vs-beanfactory">här</a>.</p>
<p>Låt oss se på ett enkelt exempel. Anta att vi ska skriva en applikation som hämtar reklamtexter (strängar) från någon typ av datakälla, för att sedan publicera dem på en ljusskylt. Vi bortser från allt det <em>riktigt</em> komplicerade, som att kommunicera med hårdvaran och sånt, och tittar på det förenklade fallet. Först har vi en datakälla med vissa egenskaper, den fungerar ungefär som en <code>Iterator&#60;String&#62;</code>, så vi modellerar gränssnittet på liknande sätt:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>public interface AdTextDataSource {
    boolean hasNext();
    String next();
}</pre>
</td>
</tr>
</tbody>
</table>
<p>Vi vet inte så mycket mer om datakällan för närvarande än att den kommer att klara av att uppfylla gränssnittet ovan. Dags att titta på konsumenten, dvs den komponent som ska hämta textsträngarna och visa upp dem på enklaste sätt:</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>public class AdTextConsumer {
    private AdTextDataSource dataSource;

    public void setDataSource(AdTextDataSource ds) {
         this.dataSource = ds;
    }

    public AdTextDataSource getDataSource() {
        return this.dataSource;
    }

    public void loopUntilDone() {
        while (getDataSource().hasNext()) {
            System.out.println(getDataSource().next());
        }
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<p>Så, var kommer textsträngarna ifrån? Ja det vet vi ju inte riktigt ännu -- det kan vara från en textfil på det lokala filsystemet, en SQL-databas, en extern webbsida, ett pollande webservice-anrop eller nåt helt annat. Men för att testa vår kod bygger vi en liten test-datakälla som lagrar strängarna i en vanlig lista i minnet.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>public class InMemoryAdTextDataSource implements AdTextDataSource {
    private List&#60;String&#62; texts = new ArrayList&#60;String&#62;();
    private int index;
    public List&#60;String&#62; getTexts() {
        return this.texts;
    }

    public void setTexts(List&#60;String&#62; texts) {
        this.texts = texts;
    }

    public String next() {
        return getTexts().get(index++);
    }

    public boolean hasNext() {
        return index &#60; getTexts().size();
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<p>Ovan ser vi att <code>AdTextConsumer</code> inte har något beroende till <code>InMemoryAdTextDataSource</code> utan bara till dess interface. Vi ser också att <code>AdTextConsumer</code> inte instansierar eller slår upp <code>InMemoryAdTextDataSource</code>, det ska vi låta Spring göra. Nedan följer ett ett exempel på hur dessa klasser kan bindas ihop med Spring. Vi skapar en fil som vi kallar för  <code>applicationContext.xml</code> med följande innehåll.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>&#60;?xml version="1.0" encoding="UTF-8"?&#62;
&#60;beans
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-2.5.xsd"&#62;

    &#60;bean id="dataSource" class="AdTextDataSource"&#62;
	&#60;property name="texts" ref="texts"/&#62;
    &#60;/bean&#62;

    &#60;bean id="consumer"
            class="AdTextConsumer"
            init-method="loopUntilDone"&#62;

        &#60;property name="dataSource" ref="dataSource"/&#62;
    &#60;/bean&#62;

    &#60;util:list id="texts"&#62;
	&#60;value&#62;text1&#60;/value&#62;
	&#60;value&#62;text2&#60;/value&#62;
	&#60;value&#62;text3&#60;/value&#62;
    &#60;/util:list&#62;
&#60;/beans&#62;</pre>
</td>
</tr>
</tbody>
</table>
<p>Vi har nu en färdig XML-konfiguration för Spring.  Den första bönan vi definierar är <code>dataSource</code>, när vi anger <code>class</code> berättar vi för Spring vilken klass som ska instansieras.</p>
<p>Genom att ange en <code>property</code> (med namnet <code>texts</code>) låter vi Spring köra <code>setTexts</code>-metoden på bönan <code>dataSource</code>, vi har här vårt första exempel på DI.</p>
<p>Bönan <code>texts</code> utgör här initialiseringsdata till <code>dataSource</code>. Hade vi haft vår initialiseringsdata i en propertyfil hade vi exempel kunnat använda Springs <a href="http://static.springframework.org/spring/docs/2.5.x/reference/xsd-config.html#xsd-config-body-schemas-util-properties">PropertiesFactoryBean</a> eller liknande. Bönan <code>texts</code> är lite speciell, Spring skapar ett vanligt <code>List</code>-objekt med värdena vi anger. Vi skulle kunna göra det på annat sätt men Spring har ett util-paket som låter oss skapa bönan på detta kortare sätt.</p>
<p>Nästa böna är <code>consumer</code> som ska kopplas ihop med bönan <code>dataSource</code>. Med <code>init-method</code> har vi infört livscykelshantering. Spring kommer automatiskt att köra metoden <code>loopUntilDone</code> så snart bönan är skapad och alla properties är satta. Motsatsen till <code>init-method</code> kan anges med <code>destroy-method</code>. Livscykelhantering kan man även uppnå genom att implementera interfacen <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/InitializingBean.html">InitializingBean</a> och <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/DisposableBean.html">DisposableBean</a>.</p>
<p>För att få igång ett program behöver vi en main-metod som sparkar igång Spring, det kan göras som följande</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>public static void main(String[] args) {
    ApplicationContext ctx =
        new ClassPathXmlApplicationContext("applicationContext.xml");
    ctx.refresh();
}
</pre>
</td>
</tr>
</tbody>
</table>
<p>Vi har nu designat våra klasser för DI, inga förekomster av <code>new</code> eller fabriker. Vi har låtit Spring ta hand om skapande av objekt, livscykelhantering och initialiseringsdata. I och med att vi inte har några beroenden till Spring, någon speciell fabrik eller implementationsklass för <code>AdTextDataSource</code> är det enkelt att skapa ett unit-test för att testa vår consumer.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>public void testSimple() {
    String[] texts = {"text1", "text2", "text3"};
    AdTextDataSource dataSource = new InMemoryAdTextDataSource();
    dataSource.setTexts(Arrays.asList(texts)); //DI

    AdTextConsumer consumer = new AdTextConsumer();
    consumer.setDataSource(dataSource); // DI
    consumer.loopUntilDone(); // Egentligen hanterat via "init-method"
    assertValidOutput(); // assert på output (inte relevant)...
}</pre>
</td>
</tr>
</tbody>
</table>
<p>(Ok, jag fuskade lite på slutet och antog att det fanns en <code>assertValidOutput()</code> som kollade att det som skrevs ut stämde -- det är inte relevant för artikeln!)</p>
<p>Här kan man säga att vi manuellt binder ihop <code>dataSource</code> och <code>consumer</code> genom metoden <code>setDataSource</code>. Om man vill testa genom att använda Spring istället så kan man starta ett context via ett JUnit-test genom att ärva någon av subklasserna till <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/AbstractSpringContextTests.html">AbstractSpringContextTests</a> där metoden <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/AbstractSingleSpringContextTests.html#getConfigLocations()">getConfigLocations</a> kan överlagras och ex returnera en referens till ovan nämnda contextfil (applicationContext.xml).</p>
<p>Av: <strong>Robert Burén</strong>,  <strong>Johan Risén</strong>, <strong>Tommy Wassgren</strong></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JBoss, webservices e Spring]]></title>
<link>http://unopuntozero.wordpress.com/2008/06/05/jboss-webservices-e-spring/</link>
<pubDate>Thu, 05 Jun 2008 20:55:00 +0000</pubDate>
<dc:creator>rootkit</dc:creator>
<guid>http://unopuntozero.wordpress.com/2008/06/05/jboss-webservices-e-spring/</guid>
<description><![CDATA[Problema: supponiamo di avere una applicazione (web o non web) basata su Spring e di voler pubblicar]]></description>
<content:encoded><![CDATA[<p>Problema: supponiamo di avere una applicazione (web o non web) basata su Spring e di voler pubblicare come web service su JBoss uno o più degli oggetti business gestiti da Spring.<br />
La prima cosa che salta all'occhio è che qualora si utilizzino le comodissime <a href="http://jcp.org/en/jsr/detail?id=181">annotazioni standard</a> per fare il deploy del web service, il vostro oggetto manager non viene istanziato tramite l'<a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html">IOC container di Spring</a>, quindi diventa sostanzialmente inutilizzabile.<br />
Una soluzione potrebbe essere convertire il progetto a Ejb3, chi può farlo lo faccia, ma chi non può? Per non parlare di chi non vuole...<br />
In questi casi il metodo conveniente è quello di derivare la vostra classe che esporrà il web service da una n-esima classe di supporto di Spring, la <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/context/support/SpringBeanAutowiringSupport.html"><span style="font-family:courier new;">SpringBeanAutowiringSupport</span>.</a> Questa classe astratta abilita l'annotazione <span style="font-family:courier new;">@Autowire</span> su qualsiasi istanza di oggetto purchè creata all'interno di una Web Application Spring-based.  In questo modo potete "iniettare" oggetti configurati nel vostro IOC container di Spring nel vostro Web Service, esattamente come se fosse esso stesso un oggetto di Spring, continuando quindi ad utilizzare il paradigma del <a href="http://en.wikipedia.org/wiki/Inversion_of_Control">inversion of control</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Dependency Injection (DI)]]></title>
<link>http://stacktrace.se/?p=216</link>
<pubDate>Fri, 30 May 2008 13:39:42 +0000</pubDate>
<dc:creator>Johan Risén</dc:creator>
<guid>http://stacktrace.se/?p=216</guid>
<description><![CDATA[Detta inlägg ingår i serien Spring från början och kommer att förklara designmönstren Inversio]]></description>
<content:encoded><![CDATA[<p>Detta inlägg ingår i serien <a href="http://stacktrace.se/2008/05/30/spring-fran-borjan-introduktion/">Spring från början</a> och kommer att förklara designmönstren <em>Inversion of Control</em> (IoC) och <em>Dependency Injection</em> (DI).</p>
<h2>Inversion of Control</h2>
<p>Inversion of Control (IoC) är egentligen ett samlingsnamn på en mängd mönster. Dessa mönster uppträder ofta i ramverk. Huvudpoängen är att det inte är den egna applikationskoden som styr programflödet utan att detta sköts av ramverket. IoC är också lite informellt känt som <em>"Hollywood Principle" – "don't call us, We'll call you."</em><br />
<!--more--></p>
<p>Traditionellt i imperativa programmeringsspråk så har applikationskoden explicit styrt programflödet. Programflödet defineras av att applikationskoden styr hela flödet som antingen är egen kod eller anrop till bibliotekskod. Bibliotekskoden kan anropa annan bibliotekskod, men typiskt aldrig den egna koden. <em>Inversion of Control</em> uppstår alltså när bibliotekskoden anropar den egna koden.</p>
<h3>Exempel på IoC</h3>
<ol>
<li>
<div>Händelsestyrd programmering (event-driven programming). En <em>main-loop</em> definerar ett tydligt flöde i vilket den egna applikationskoden kan kopplas in. (exempelvis Swing)</div>
</li>
<li>
<div>JUnit. När du skriver ett testfall enligt JUnit 3.8+ så skapar du en testklass som ärver ramverksklassen <code>TestCase</code>. Du utvecklar en eller flera testmetoder <code>testSomething</code> och <code>testSomethingElse</code>. Ramverket tillhandahåller <code>setUp</code>- och <code>tearDown</code>-metoder där du kan lägga in initiering och uppstädningskod. Men det är inte du som kör testet utan detta gör ramverket.</div>
</li>
</ol>
<h2>IoC och beroenden</h2>
<p>Definitionen på IoC ovan är betydligt bredare än vad man nu för tiden menar när man använder begreppet IoC. Vanligtvis talar man om att externt, via en container, hantera skapandet av komponenter och dess beroenden.</p>
<p>IoC kan grovt delas in i två kategorier nämligen Dependency Lookup och Dependency Injection (DI) vilka båda beskrivs nedan.</p>
<p>Traditionellt sett har skapande av komponenter och dess beroenden skett i de faktiska komponenterna såsom i detta exempel där klassen <code>Foo</code> skapar en instans av typen <code>Bar</code> och dessutom exekverar det logiska programflödet via metoden <code>executeSomething</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>01: public class Foo {
02:     public void doSomething() {
03:         Bar bar = new BarImpl();
04:         bar.executeSomething();
05:     }
06: }</pre>
</td>
</tr>
<tr>
<td>
<div class="fig">Figur 1: Foo på klassiskt sätt</div>
</td>
</tr>
</tbody>
</table>
<p>I Figur 1 visas hur en instans av typ <code>BarImpl</code> skapas och därigenom så har klassen <code>Foo</code> ett hårt beroende till en viss typ av implementation av <code>Bar</code>-objekt.</p>
<p>Syftet med att använda IoC för att hantera skapandet av komponenter är att:</p>
<ul>
<li>Minimera "glue code" dvs kod som endast finns för att "limma ihop" applikationen.</li>
<li>Skapa komponenter på ett enhetligt och kontrollerat sätt.</li>
<li>Hantera beroenden externt så att de inte behöver vara kända av den faktiska javakoden.</li>
<li>Förbättra testbarhet. Genom att skapandet av objekt hanteras externt så kan implementationer av olika objekt enkelt bytas ut vid testning med hjälp av <a href="http://en.wikipedia.org/wiki/Mock_object" target="_blank">mock objects</a>.</li>
<li>Tvinga fram en bra applikationsdesign.</li>
</ul>
<h3>Dependency Lookup</h3>
<p>Dependency lookup är en form av IoC som har funnits länge och använts på många olika sätt. En fabrik eller ett register (factory/registry) erbjuder en applikation att koppla ihop en mängd objekt/komponenter utan att exponera för mycket om hur dessa objekt sitter ihop eller vilka beroenden de ingående objekten har. I stället för att sprida denna "create kod" i hela applikationen så kan skapandet modulariseras. Klienten anropar helt enkelt en metod på en fabrik för att få ett färdigihopkopplat och konfigurerat objekt. Klientkoden har endast beroende till fabriken och det objekt som skapas.</p>
<p>Det finns nackdelar med att använda fabriker varav en är att man måste skriva sin fabrikskod. Det kan tyckas trivialt men det blir många klasser som skrivs i onödan och det finns alltid risk för fel. Om vi tittar på ett typiskt användande av en fabrik.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>Bar ins = (Bar) MyObjectFactory.getInstance("myBar");</pre>
</td>
</tr>
<tr>
<td>
<div class="fig">Figur 2: Användning av fabrik</div>
</td>
</tr>
</tbody>
</table>
<p>Värt att notera är att vi har en hård referens till fabriken vilket är lite tråkigt. Att mocka fabriken är svårt då vi använder en statisk metod. Att byta implementerande klass i sina testfall kan vara olika svårt beroende på hur man implementerat fabriken. Har vi gjort fabriken lite smart så att den tex väljer vilken klass den ska instansiera utifrån en XML-fil kan man byta implementation utan en egen fabriksimplementation för test.</p>
<p>I detta fall måste vi aktivt välja i koden vilken instans ("myBar") vi vill ha (och stava rätt), kanske kontrollera att den inte är null och att akta oss för eventuella <code>ClassCastExceptions</code>. Även komplexiteten i detta inte är så stor vore det mycket bättre om vi slapp den för att undvika ev fel och boiler plate kod. Den som har gjort JNDI-uppslag kan notera att mönstret är detsamma, båda är exempel på Dependency Pull, en variant av Dependency Lookup.</p>
<p>Ett annat typfall på hur man gjort innan DI är användande av fabriksmetoder som i <a href="http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html">Singleton pattern</a> (även känt under synonymet <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/">Evil singleton pattern)</a>. Ett av huvudproblemen i användningen av detta mönster är den dåliga testbarheten pga att statiska metoder används som är svåra att byta ut under test.</p>
<h3>Dependency Injection</h3>
<p>Dependency injection (DI) är den andra formen av IoC gällande att skapa och hantera komponenter. Med DI är det ramverket som styr algoritmen för hur beroenden mellan ingående delar löses upp.</p>
<p>Med DI skriver man mindre kod och det finns nästan inga hårda beroenden till ramverket. När det gäller Spring kan man förenklat säga att ramverket redan tillhandahåller all den fabriks- och lookup-kod du behöver.</p>
<p>DI-containern (exempelvis Spring) kommer att vilja injicera instanser antingen i en konstruktor eller med getter/setter metoder till din klass vilket betyder att den lilla kod man skriver är mycket enkel och kan automatgenereras av en bra IDE. Med en DI-container kan man till skillnad från i Dependency Lookup fallen ovan utveckla/testa utan beroenden till en extern container. Nedanstående exempel visar hur klassen <code>Foo</code> exponerar en setter-metod som kommer att anropas av DI-containern där <code>Bar</code>-objektet sätts. Observera att klassen <code>Foo</code> nu inte har någon kunskap om hur man skapar <code>Bar</code>-objekt och den hårda kopplingen till <code>BarImpl</code> är borta. Detta hanteras nu istället av DI-containern.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>01: public class Foo {
02:     private Bar bar;
03:
04:     // setter method invoked by the DI-container
05:     public void setBar(Bar bar) {
06:         this.bar = bar;
07:     }
08:
09:     public void doSomething() {
10:         bar.executeSomething();
11:     }
12: }</pre>
</td>
</tr>
<tr>
<td>
<div class="fig">Figur 3: Foo med setter-metod</div>
</td>
</tr>
</tbody>
</table>
<p>Nästa del i denna artikelserie visar exempel på hur man kan använda <a href="http://stacktrace.se/2008/06/09/spring-som-di-ramverk-sfb/">Spring som DI-container</a>.</p>
<p>Nedanstående exempel visar hur enkelt det är att testa klassen <code>Foo</code> med en enkel testvariant av <code>Bar</code>-interfacet. På rad 5 används en form a DI direkt i koden. Om ett fabriksmönster eller direkt instansiering hade använts av klassen <code>Foo</code> hade det blivit betydligt mer komplicerat att mocka objektet <code>Bar</code>.</p>
<table border="0" bgcolor="#eeeeee">
<tbody>
<tr>
<td>
<pre>01: public class FooTest extends TestCase {
02:     public void testSomething() {
03:         Foo foo = new Foo();
04:         TestBar testBar = new TestBar();
05:         foo.setBar(testBar);
06:         foo.doSomething();
07:         assertTrue(testBar.count &#62; 0);
08:     }
09:
10:     public static class TestBar implements Bar {
11:         int count = 0;
12:
13:         public void executeSomething() {
14:             count++;
15:         }
16:     }
17: }</pre>
</td>
</tr>
<tr>
<td>
<div class="fig">Figur 4: JUnit-test och DI</div>
</td>
</tr>
</tbody>
</table>
<p><br></p>
<h3>Dependency Lookup eller Dependency Injection</h3>
<p>Så vad ska man då välja, Dependency Lookup eller DI? Om man använder Dependency Lookup så finns det hårda beroenden till det ramverk som man använder eller de fabriker som måste skapas. Det blir större mängd "glue code" och koden blir inte lika enkel att testa. Därför bör DI användas om möjligt.</p>
<p>Typiska exempel på vad en DI-container hanterar åt dig är:</p>
<ul>
<li> Hur vi får tag i referenser till andra objekt eller komponenter</li>
<li>Åtkomst till systemresurser som exempelvis filsystem</li>
<li>Hur ett objekt får sin konfiguration eller sina initieringsparametrar</li>
<li>Livscykelhantering, dvs när och vem som "startar" och "stoppar" ett objekt</li>
<li>Eftersom DI-containern skapar objekt kan proxies, aspekter, fasader och dylikt konfigureras dynamiskt. I denna serie kommer vi senare att blogga om aspekter i artikeln Introduktion till Spring AOP.</li>
</ul>
<p>Allt detta är saker du inte vill och inte behöver hantera i din applikationskod!</p>
<p>Källor</p>
<ul>
<li>Martin Fowler om Inversion of Control - <a href="http://martinfowler.com/articles/injection.html">http://martinfowler.com/articles/injection.html</a></li>
</ul>
<p>Av: <strong>Per Rasmussen</strong>, <strong>Johan Risén</strong> och <strong>Tommy Wassgren</strong>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring från början - introduktion]]></title>
<link>http://stacktrace.se/?p=205</link>
<pubDate>Fri, 30 May 2008 13:34:36 +0000</pubDate>
<dc:creator>Robert Burén</dc:creator>
<guid>http://stacktrace.se/?p=205</guid>
<description><![CDATA[Idag startar vi en spännande artikelserie: Spring från början! Vi är några Stacktrace.se-skribe]]></description>
<content:encoded><![CDATA[<p>Idag startar vi en spännande artikelserie: <em>Spring från början!</em> Vi är några Stacktrace.se-skribenter som planerar att tillsammans ge en steg-för-steg-introduktion till Spring. Vi kommer att börja från grunden med att beskriva designmönstret Dependency Injection och varför det är relevant för Spring. Sen kommer vi att bygga vidare med olika sätt att sätta ihop och konfigurera Spring-applikationer och fortsätta med att gå in på Springs utmärkta stöd för andra ramverk och tekniker.</p>
<p>Artikelserien vänder sig i första hand till nybörjare och relativt oerfarna Spring-utvecklare, men alltefter som vi går in på djupet i olika teknikområden hoppas och tror vi att  det ska finnas intressant information även för de mer erfarna.</p>
<p>Vi kommer att uppdatera den här texten med en aktuell innehållsförteckning varje gång ett nytt avsnitt finns tillgängligt, så sätt gärna ett bokmärke här!</p>
<h2>Innehållsförteckning</h2>
<ul>
<li>Spring från början, introduktion (den här texten)</li>
<li><a href="http://stacktrace.se/2008/05/30/dependendy_injection_d/">Dependency Injection (DI)</a></li>
<li><a href="http://stacktrace.se/2008/06/09/spring-som-di-ramverk-sfb/">Spring som DI-ramverk</a></li>
<li><a href="http://stacktrace.se/2008/06/16/spring-konfiguration-via-annotations/">Konfigurera med annotations</a></li>
<li><a href="http://stacktrace.se/2008/08/19/spring-jdbc/">Spring JDBC</a></li>
<li><a href="http://stacktrace.se/2008/08/27/spring-jms/">Spring JMS</a></li>
<li>Aspektorientering med Spring (kommer snart)</li>
<li>Hibernatestödet i Spring (planerad)</li>
<li>Spring Security (planerad)</li>
<li>Spring för webbappar (planerad)</li>
<li>Spring Dynamic Modules (OSGi) (planerad)</li>
<li>Service Exporters i Spring (planerad)</li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Palestra sobre JavaBB no JUGDay em Porto Alegre]]></title>
<link>http://daltondecamargo.wordpress.com/?p=15</link>
<pubDate>Tue, 27 May 2008 00:47:39 +0000</pubDate>
<dc:creator>daltondecamargo</dc:creator>
<guid>http://daltondecamargo.wordpress.com/?p=15</guid>
<description><![CDATA[
Neste sabado ( 31/maio/2008 ) eu estarei apresentando as 16h no evento JugDay o JavaBB, projeto bra]]></description>
<content:encoded><![CDATA[<p><img src="http://www.javabb.org/search_files/_logo.gif" alt="" width="212" height="90" /><br />
Neste sabado ( 31/maio/2008 ) eu estarei apresentando as 16h no evento JugDay o <a href="http://www.javabb.org/" target="_blank">JavaBB</a>, projeto brasileiro baseado em java com a finalidade de ser um sistema de forum de discussoes.<br />
A finalidade desta palestra sera apresentar as tecnologias utilizadas no projeto e os padroes adotados durante a evolucao da ferramenta conforme as necessidades que foram surgindo na medida que fomos desenvolvendo o projeto.<br />
Um dos frameworks adotados no projeto é o consagrado Spring Framework, framework ao qual eu tive a felicidade de traduzir e revisar o primeiro livro em Portugues. (Spring in Action)</p>
<p>Para quem tiver interesse de saber mais sobre o evento, visite o link:<br />
<a href="http://www.javafree.org/news/view.jf?idNew=3744">http://www.javafree.org/news/view.jf?idNew=3744</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Χειρισμός transactions εμπλέκοντας EJB, Hibernate και Spring Framework]]></title>
<link>http://routis.wordpress.com/2008/05/17/%ce%a7%ce%b5%ce%b9%cf%81%ce%b9%cf%83%ce%bc%cf%8c%cf%82-transactions-%ce%b5%ce%bc%cf%80%ce%bb%ce%ad%ce%ba%ce%bf%ce%bd%cf%84%ce%b1%cf%82-ejb-hibernate-%ce%ba%ce%b1%ce%b9-spring-framework/</link>
<pubDate>Sat, 17 May 2008 10:49:19 +0000</pubDate>
<dc:creator>routis</dc:creator>
<guid>http://routis.wordpress.com/2008/05/17/%ce%a7%ce%b5%ce%b9%cf%81%ce%b9%cf%83%ce%bc%cf%8c%cf%82-transactions-%ce%b5%ce%bc%cf%80%ce%bb%ce%ad%ce%ba%ce%bf%ce%bd%cf%84%ce%b1%cf%82-ejb-hibernate-%ce%ba%ce%b1%ce%b9-spring-framework/</guid>
<description><![CDATA[Είναι γνωστό ότι στην περίπτωση που κάποιος υλοποιεί EJ]]></description>
<content:encoded><![CDATA[<p><img style="float:left;margin:5px;" src="http://routis.files.wordpress.com/2008/05/dukeaskeith-daylightsmall.png" alt="" width="87" height="72" />Είναι γνωστό ότι στην περίπτωση που κάποιος υλοποιεί EJB με τη βοήθεια του Spring Framework, θα πρέπει να επιλέξει αν το χειρισμό των transactions θα τον πραγματοποιούν τα EJB (container managed transactions ή user managed transactions), είτε το Spring Framework. Οι δυο επιλογές δεν είναι ισοδύναμες, μιας και μόνο χρησιμοποιόντας το Spring Framework μπορείς να δοκιμάσεις τον κώδικά σου κι εκτός από JEE αpplication server.<br />
Αυτά είναι λίγο πολύ γνωστά, σε όσους ασχολούνται με το Spring Framework. Αυτό όμως που δεν είναι γνωστό είναι πως γίνεται η διαχείριση των transactions στην περίπτωση όπου έχουμε EJB όπου χειρίζονται Spring POJO's τα οποία με τη σειρά τους χρησιμοποιούν το Hibernate.<br />
Η σπάνια αυτή περίπτωση, δυστυχώς δεν αναφέρεται η βιβλιογραφία του Spring Framework. Ευτυχώς όμως, υπάρχει μια εκτενής περιγραφή του πως πρέπει να ρυθμιστεί το Spring Context <a href="http://kmazut.blogspot.com/2008/04/integrating-cmt-ejb-spring-hibernate.html">εδώ</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Understanding Spring Framework Hierarchical Context]]></title>
<link>http://fantastic.wordpress.com/?p=31</link>
<pubDate>Thu, 15 May 2008 22:14:53 +0000</pubDate>
<dc:creator>fantastic</dc:creator>
<guid>http://fantastic.wordpress.com/?p=31</guid>
<description><![CDATA[Not many people are familiar with the support that Spring framework has for hierarchical context.  T]]></description>
<content:encoded><![CDATA[<p>Not many people are familiar with the support that Spring framework has for hierarchical context.  The question is why do we need such feature.  This feature is useful in the scenario where your product has multiple web applications and all of them depend on a common framework or library.  Instead of deploy that framework or library in each web application, you can deploy it in the Tomcat top level class loader, which affectively makes the framework or library available to all web applications deployed in that Tomcat server.</p>
<p>This is when hierarchical context feature comes to the rescue.  A very good write up about this feature is at this <a href="http://www.codechimp.net/?p=22" target="_blank">blog</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Springmodules cache]]></title>
<link>http://cygni.wordpress.com/?p=230</link>
<pubDate>Wed, 07 May 2008 11:53:55 +0000</pubDate>
<dc:creator>Johan Risén</dc:creator>
<guid>http://cygni.wordpress.com/?p=230</guid>
<description><![CDATA[Springmodules cache
Springmodules är en samling av verktyg och tillägg till Spring Framework. Jag ]]></description>
<content:encoded><![CDATA[<p><strong>Springmodules cache</strong><br />
Springmodules är en samling av verktyg och tillägg till Spring Framework. Jag halkade in på att använda detta då vi i mitt projekt använde OSCache programatiskt och vi insåg att det blev mycket boilerplate kod. Här är ett typiskt <a href="http://www.opensymphony.com/oscache/wiki/API%20Usage.html">användande av OSCache</a>.<br />
<!--more--><br />
En lösning är att använda springmodules cache-stöd för OSCache, EHCache m.fl. Det är en AOP lösning där målobjektet får en proxy som fångar anrop till utvalda metoder, gör en nyckel av anropet och cachar resultatet. Mycket bekvämt!<br />
I sin annotering anger man vilken cache/flush modell som skall användas, modellerna skapar man med fördel i sin spring applicationcontext och innehåller konfiguration för exempelvis hur länge ett objekt ska stanna i cachen. Modellerna skiljer sig lite beroende på val av cache.</p>
<p>Man kan låta proxies automatgenereras utifrån cache/flush annotations eller så kan man explicit skapa proxies per böna. </p>
<p>Ett varningens finger dock, även om det var mycket bekvämt kändes det inte helt moget. Ett ex är att det ännu (v0.9) inte går att flusha cachen på lägre nivå än cache/grupp nivå. Ännu allvarligare är att jag upplevde en minnesläcka i ramverkets interna metadata cachning, dvs cachningen av annotations. Att sluta använda annotations och istället använda proxy-konfiguration i xml går runt problemet. Ytterligare en frustration som tyder på att lösningen inte är helt genomarbetat beskrivs <a href="http://www.jroller.com/habuma/entry/fixing_spring_modules_xsd_errors">här</a><br />
Sammanfattningsvis, bra tänkt men vänta gärna några versioner.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Walkin For Java Professionals on 26th April]]></title>
<link>http://thewalkin.wordpress.com/?p=118</link>
<pubDate>Sat, 19 Apr 2008 05:46:52 +0000</pubDate>
<dc:creator>govjobs</dc:creator>
<guid>http://thewalkin.wordpress.com/?p=118</guid>
<description><![CDATA[Company Name : Tribal Fusion R&amp;D India Pvt Ltd.
Skills Required : Java, J2EE, Spring Framework ,]]></description>
<content:encoded><![CDATA[<p><strong>Company Name :</strong> Tribal Fusion R&#38;D India Pvt Ltd.</p>
<p><strong>Skills Required :</strong> Java, J2EE, Spring Framework , struts , hibernate, &#38; Oracle Database</p>
<p><strong>Experience Required :</strong> 3 - 6 Year(s)<br />
<strong>Job Location :</strong> NOIDA<br />
<strong>Walk-in Date :</strong> 26 April 2008<br />
<strong>Walk-in Time :</strong> 10:00 a.m - 05:00 p.m<br />
<span style="text-decoration:underline;">Job Description :</span></p>
<p><strong>Candidates for this position should have the following skills:</strong></p>
<ol>
<li>The candidate should have a BE/BTech /MTech from IIT/RECBITS or any premiere institute in Computer Science/Electronics with 3 - 6+ yrs experience.</li>
<li>Expertise in writing server side Java code. Must have expertise in Core Java - multi- threading, RMI, transaction handling, data structures, distributed architecture &#38; Servlets.</li>
<li>Good understanding or familiarity with standard data structures such as maps, collections, trees.</li>
<li>Experience writing Oracle database code for persistent Java objects. This includes a strong understanding of JDBC and SQL.</li>
<li>Experience using a framework such as Struts, Spring, Hibernate is a plus.</li>
</ol>
<p><a title="Walk-in Venue and More Information" href="http://www.thewalkin.com/2008/523_java-proffesionals-walk-in-by-tribal-fusion.html" target="_blank">For more Information</a></p>
]]></content:encoded>
</item>

</channel>
</rss>
