Tagebuch eines Technikers

Thursday, May 15, 2008

First steps with Spring and Maven

I just started to get acquainted with Spring and Maven two, after currently working on a project using Spring and Hibernate with the Appfuse maven2 archetype. Since this archetype gives me some headache when trying to compile and run the project, I decided to restart from the basics in order to get a grip on all the technology we're using.

I start off with the tutorials and demo projects of the book Beginning Spring Framework 2. You can find all the demos online.

The first example can be found in the directory src\chapter1\springfirst. It is a modularized calculator, taking command line arguments and -- depending on the configuration -- either adds or multiplies the arguments.

The pom.xml file in the base directory contains all dependencies needed, so Maven2 will download these dependencies to compile and run the application. The compilation process ist started by calling
mvn compile
on the command line. Dependencies (spring-aspects, spring-aop, junit) will be downloaded upon the first call.

The target directory now contains the compiled code and needed resources. The example can be started by calling

mvn exec:java -Dexec.mainClass=com.wrox.begspring.CalculateSpring -Dexec.args="3000 3"

This starts the application and calculates the result (either add oder multiply 3000 and 3).

How it works:

The main class CalculateSpring uses Spring in order to execute the multiplication. It uses a bean factory that can be configured in the bean.xml file. The bean.xml looks something like this:

<bean id="screen" class="com.wrox.begspring.ScreenWriter" />
<bean id="multiply" class="com.wrox.begspring.OpMultiply" />
<bean id="add" class="com.wrox.begspring.OpAdd" />

<bean id="opsbean" class="com.wrox.begspring.CalculateSpring">
<property name="ops" ref="multiply" />
<property name="writer" ref="screen"/>
</bean>
Here, the beans are registered and wired.

How the program execution works: Spring creates instances of ScreenWriter, OpMultiply and OpAdd and then another instance of CalculateSpring where it sets references to the defined writer (screen) and operation (multiply). If you change the last part of beans.xml to
<bean id="opsbean" class="com.wrox.begspring.CalculateSpring">
<property name="ops" ref="add" />
<property name="writer" ref="screen"/>
</bean>
and execute the program, you can see that the operation has changed from multiplication to addition.

These are the first steps with Spring and its dependency injection mechanism. More to come, hopefully.

Edit: There is another way of wiring the objects, namely auto-wiring by type. This looks something like this:
<bean id="screen" class="com.wrox.begspring.ScreenWriter" />
<bean id="add" class="com.wrox.begspring.OpAdd" />
<bean id="opsbean" class="com.wrox.begspring.CalculateSpring" autowire="byType" />
Put this in your beans.xml and the wiring will happen automagically.

No comments: