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 compileon 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" />Here, the beans are registered and wired.
<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>
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">and execute the program, you can see that the operation has changed from multiplication to addition.
<property name="ops" ref="add" />
<property name="writer" ref="screen"/>
</bean>
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" />Put this in your beans.xml and the wiring will happen automagically.
<bean id="add" class="com.wrox.begspring.OpAdd" />
<bean id="opsbean" class="com.wrox.begspring.CalculateSpring" autowire="byType" />
No comments:
Post a Comment