LDSTechForumProjects

Introduction to Spring

Spring is a technology meant to simplify J2EE development and provide a lighter weight and more loosely coupled development paradigm than its EJB counterpart. It does this by enabling application development based on POJOs (Plain Old Java Objects). Spring has weathered the test of time, and change, unlike many other frameworks, which is a testament to its value and vision. Additionally, Spring is the heart of the Java Stack, and we will be discussing many of the benefits of using Spring, as well as many of the simplifications in application development and maintenance that Spring provides.

Prerequisites

  • Must have previously completed the Introduction to the Java Stack training.
  • Basic knowledge of Java language.
  • Basic knowledge of XML syntax and structure.
  • A workstation running Windows, Linux, or Mac OS.
  • A desire to learn.

Outline

Overview

  • Why the Spring Framework?

Inversion of Control (IoC) container

  • Bean Declaration
  • Application Context

Dependency Injection (DI)

  • Setter Injection
  • Constructor Injection

Bean Scopes

  • Singleton
  • Prototype


Slide Deck

Media:IntroductionToSpring.pptx‎

Bean Configuration Presentation

Get Adobe Flash player

Lab 1 Bean Configuration

Create a basic Spring enabled project

  • File -> New -> Maven Project -> Next
  • In filter search for maven-archetype-quickstart and select it
  • Group Id: org.lds.training
  • Artifact Id: spring-training (or something like unto it)
  • Version: 1.0
  • Package: org.lds.training

Or if you are using IntelliJ you can run the following archetype command from the command line:
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.1 -DgroupId=org.lds.training -DartifactId=spring-training -Dversion=1.0

Add the following dependency to your pom.xml

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>3.0.5.RELEASE</version>
</dependency>

Configure a bean definition to be managed by the Spring container (application context)

  • Create a class named SomeBean with a method printSomething()
    public class SomeBean {
         public void printSomething() {
              System.out.println("something");
         }
    }
  • Create a bean definition xml file named beans.xml in src/main/resources (add resources folder if not there)
    <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-3.0.xsd">
        <!-- Place bean definitions here -->
    </beans>
  • Add a bean definition for the class you created
     <bean class="org.lds.training.SomeBean" />
  • Configure your application context by loading the bean definition file created above
    public class SpringTester {
        public static void main( String[] args ) {
    	    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        }
    }
  • Retrieve the bean from the context and call the print something method on it
    SomeBean someBean = context.getBean(SomeBean.class);
    someBean.printSomething();
  • Run by right clicking on the SpringTester class and selecting Run As -> Java Application
  • Modify this example to get a bean by id (remember to specify an id in the bean definition file)

So what did this buy us? Why didn't we just call new SomeBean().printSomething();

Lab 1 Solution

Get Adobe Flash player

Dependency Injection Presentation

Get Adobe Flash player

Lab 2 Dependency Injection

Inject one bean into another to accomplish a coordinated result

  • Create a Rabbit class as follows
    public class Rabbit {
        private float weight;
        private String name;
    
        public Rabbit(float weight) {
            this.weight = weight;
        }
	public float getWeight() {
	    return weight;
	}
	
	public String getName() {
	    return name;
	}
        public void setName(String name) {
    	    this.name = name;
        }
    }
  • Create a Farm class
    public class Farm {
        private List<Rabbit> rabbits;
    
        public void setRabbits(List<Rabbit> rabbits) {
            this.rabbits = rabbits;
        }
    }
  • Create a farm bean definition and inject some rabbits
    <bean id="farm" class="org.lds.training.Farm">
        <property name="rabbits">
	    <list>
                 <bean class="org.lds.training.Rabbit">
		     <constructor-arg name="weight" value="10.5" />
                 </bean>
                 <bean class="org.lds.training.Rabbit">
		     <constructor-arg name="weight" value="2.25" />
                 </bean>
                 <bean class="org.lds.training.Rabbit">
		     <constructor-arg name="weight" value="5.0" />
                 </bean>
            </list>
        </property>
    </bean>
  • Add a method to the Farm that calculates how many lbs of rabbit pellets it will take to feed the rabbits on the farm for 1 day (use 1% of their weight to calculate this)
    public void calculatePelletWeight() {
    	float total = 0f;
    	if (rabbits != null) { 
	    	for (Rabbit rabbit : rabbits) {
	    		total += rabbit.getWeight();
	    	}
    	}
    	System.out.println("Total pellet weight in lbs per day: " + total * .01);
    }
  • Load the bean definition file into the application context, get the farm bean and call the calculatePelletWeight() method

Lab 2 Solution

Get Adobe Flash player

Bean Scopes Presentation

Get Adobe Flash player

Lab 3 Bean Scopes

Demonstrate the difference between singleton and prototype scopes

  • Add a private int mealCount member variable to your Rabbit class
  • Add a printMealCount method that increments the meal count and prints it out
    public void printMealCount() {
    	System.out.println(++mealCount);
    }
  • Create a singleton bean definition for Rabbit
  • Create a prototype bean definition for Rabbit
  • Demonstrate how singleton and prototype scopes differ, by getting each bean multiple times and calling printMealCount()
    System.out.println("prototype output");
    context.getBean("prototypeRabbit", Rabbit.class).printMealCount();
    context.getBean("prototypeRabbit", Rabbit.class).printMealCount();
    context.getBean("prototypeRabbit", Rabbit.class).printMealCount();
    	
    System.out.println("\r\nsingleton output");
    context.getBean("singletonRabbit", Rabbit.class).printMealCount();
    context.getBean("singletonRabbit", Rabbit.class).printMealCount();
    context.getBean("singletonRabbit", Rabbit.class).printMealCount();

Lab 3 Solution

Get Adobe Flash player
This page was last modified on 6 June 2011, at 23:02.

Note: Content found in this wiki may not always reflect official Church information. See Terms of Use.