原文地址:http://gabriel.jarchitect.org/spring/index.html
60 sec to Spring [TOC]
Bean Tutorial 1 - Hello World Bean
This tutorial show you how to call a Hello World Bean using Spring IoC.
Step 1: Create a HelloBean.java in src
org/jarchitect/spring/tutorial1/HelloBean.java
package org.jarchitect.spring.tutorial1; public class HelloBean { public String sayHelloWorld() { return "Hello World"; } } |
Step 2: Specify the HelloBean class in the bean.xml
bean.xml
version="1.0" encoding="UTF-8"?> beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> jarchitect Spring Tutorial 1 < font> id= "helloBean" class= "org.jarchitect.spring.tutorial1.HelloBean" /> |
Step 3: Create a Main.java in src
org/jarchitect/spring/tutorial1/Main.java
package org.jarchitect.spring.tutorial1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import org.springframework.beans.factory.xml.XmlBeanFactory; public class Main { public static void main(String[] args) { try { //Read the configuration file InputStream is = new FileInputStream("bean.xml"); XmlBeanFactory factory = new XmlBeanFactory(is); //Instantiate an object HelloBean helloBean = (HelloBean) factory.getBean("helloBean"); //Execute the public method of the HelloBean System.out.println(helloBean.sayHelloWorld()); } catch (FileNotFoundException e) { e.printStackTrace(); } } } |
Step 4: Use an ANT script to build and execute the Main class. Just run ant from the command prompt will do the trick.
Below are the output from ANT.
C:/60sec2Spring/SpringTutorial1>ant Buildfile: build.xml build: [javac] Compiling 2 source files to C:/60sec2Spring/SpringTutorial1/bin run: [java] May 18, 2004 2:25:14 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions [java] INFO: Loading XML bean definitions from (no description) [java] May 18, 2004 2:25:15 PM org.springframework.beans.factory.support.AbstractBeanFactory getBean [java] INFO: Creating shared instance of singleton bean 'helloBean' [java] Hello World BUILD SUCCESSFUL Total time: 3 second |
Done.