Jumpstart Spring

3

Since Lucas already gave an in-depth review of the Spring workshop, I’ll take the breadcrumbs ;-(
After some years of Java/j2ee developing Spring comes for me at the right moment. I start getting annoyed by the fact that with J2EE development a lot of time is spend not on the actual problem but on excessive plumbing code, (e.g. using ejb’s, jndi, jms etc.), re-inventing/re-implementing the wheel, code-replacement for testing purposes etc. etc. The Spring framework can offers a solution for this. As many people already pointed out, it is difficult to describe precisely what Spring is. One thing is for sure, it is modular and it aims at making j2ee development easier.

The interesting thing is that in many places Spring is not intrusive. The dependencies with other objects are configured in xml files and injected when needed. For example, for testing purposes it is quite easy that a data access objects returns mockobjects instead of data from the database. It does this by using the Inversion of Control (IoC) principle: let de environment take care of the plumbing. This can be considered as the core of Spring (although it is not necessary to use it when using Spring). Off course, the non intrusiveness also has a downside. Since there is no plumbing it is also no ‘real’ j2ee code and therefore cannot be used in another j2ee environment without adding coding.

The jdbc components are actually a set of utility classes around the actual JDBC code or the ORM framework like Hibernate, Toplink or others that you use. Instead of writing

import java.sql.*;
import javax.sql.*;
import javax.naming.*;
public class RunAQuery{
    public List getList() {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List rows = new ArrayList();
        try {
            Context ic = new InitialContext();
            DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/testDatabase);
            con = ds.getConnection();
            pstmt = con.prepareStatement ("select * from emp");
            rs = pstmt.execute();
            while (rs.next()) {
                Employee e = new Employee();
                e.setId   (rs.getLong(1));
                e.setName (rs.getString(2));
                    //  continue reading ResultSet
                rows.add(e);
            }
        } catch (SQLException e) {
            // handle exception
        } catch (NamingException e) {
            // handle exception
        } finally {
            try {
                rs.close();
                pstmt.close();
                con.close();
            } catch (SQLException e1) {
                // no action needed
            }
        }
        return rows;
    }
}

it is enough to write:

import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class RunAQuery {
    private DataSource dataSource;

    public List getList() {
        jt = new JdbcTemplate(dataSource);
        List rows = jt.queryForList("select * from emp");
        return rows;
    }
        // method to inject the datasource
        // this must be configured
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}

No more TCFTC (try catch finally try catch) blocks anymore :-), no more JDBC plumbing and our own frameworks, easy testible and improved error-handling. The general SQLException has been replaced by using unchecked and specialized Exceptions like the DataIntegrityViolationException for a duplicate key constraint error instead instead of checking the errorcode for Oracle’s ORA-00001.

The sheer number of options (and often multiple ways of doing something) in Spring can be quite overwhelming, but the modular and non-intrusive ‘nature’ makes it possible to start with only a few components like the jdbc component and use the rest later. It also integrates with a lot of existing frameworks like Hibernate, iBatis, Struts, Velocity, Tapestry etc.

My favorites for starting with Spring are:
– the jdbc components
– resource handling
– testing
– remoting

For now I only scratched the surface of Spring. The 4 day course provided an excellent overview of all the components and all the possibilities. The course is not easy, it’s high-level, up-speed and a lot of subjects are covered and often also really in-depth, but it is really worthwhile. Rod Johnson and Alef Arendsen and the others of Interface21 are experts, not only only on Spring, and open for discussion, suggestions and advice.

References:
Spring framework Website
Interface21
article by Rod Johnson on theServerside

Share.

About Author

Aino Andriessen is a consultant on Enterprise Java, ADF, PL/SQL, XML, and SOA development and is Expertise Lead on Application Lifecycle Management (ALM). He has a strong interest in ADF, SOA, Maven, architecture, quality management, delivery and application lifecycle management. Aino publishes on the AMIS technology blog and has been a presenter at the ODTUG Kaleidoscope, Oracle Open World and UKOUG TechEbs.

3 Comments

  1. Hi,
    In case if an exception arises while using Spring JDBC (e.g.: invalid column name specified
    in the SQL query) & I have to display a user-freindly message on the screen, then how do I catch
    an exception & send it upto the presentation layer? Please explain with a sample code.

  2. Wouter van Reeven on

    It can be made even shorter :


    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    import java.util.List;

    public class RunAQuery extends JdbcDaoSupport {

    public List getList() {
    return getJdbcTemplate().queryForList(“select * from emp�);
    }
    }

    ;-)

  3. You could make the example even more compact if you extend JdbcDaoSupport that handles creating JdbcTemplate for you.

    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    import java.util.List;

    public class RunAQuery extends JdbcDaoSupport {

    public List getList() {
    List rows = getJdbcTemplate().queryForList(“select * from emp”);
    return rows;
    }
    }