Download NetBeans!

20080323 Sunday March 23, 2008

Hello Spring (Part 1)

My first encounter with Spring is through its Util schema. I used NetBeans IDE 6.1 Beta, since this version of NetBeans IDE sports a set of features specifically for Spring, for the first time. There's support for web applications (which I will discuss in a future blog entry), but also for Java SE applications. Here's my first Spring configuration file in a Java SE application:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">
           
    <util:list id="emails">
        <value>john@smith.org</value>
        <value>jack@harry.org</value>
        <value>peter@piper.org</value>
        <value>pavel@prochazka.org</value>
    </util:list>
    
</beans>

To help me while coding the above file, I have context-sensitive code completion to help me:

And here's how I created it, i.e., using a new template...

... which also lets me choose one or more namespaces, so that I don't need to think about the header of the Spring configuration file at all:

Here's my simple Java class for accessing (and using) the above Spring configuration file:

package hellospring;

import java.util.ArrayList;
import java.util.Iterator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class Main {

    public static void main(String[] args) {
        BeanFactory factory = new XmlBeanFactory(new FileSystemResource("src/hellospring/demo.xml"));
        ArrayList list = (ArrayList) factory.getBean("emails");
        Iterator it = list.iterator();
        int count = 0;
        while (it.hasNext()) {
            count = count + 1;
            System.out.println("Email " + count + ": " + it.next().toString());
        }
    }
    
}

I am also able to get Java code completion in my Spring configuration file, whenever I need it, specifically for class attributes:

And then I can simply click the class references, which then results in the class being opened in the editor:

Finally, I can organize my Spring configuration files. On the Project Properties node of Java SE applications, there's a new node that appears when the Spring JARs are on my classpath, for grouping my Spring configuration files:

Finally, for more info on the new Spring support, see Improved Spring Framework Support in NetBeans 6.1: XML-Config Files in Ramon Ramos's blog.

Mar 23 2008, 08:05:56 AM PDT Permalink