现在的位置: 首页 > 综合 > 正文

Spring学习——Hello World

2013年04月27日 ⁄ 综合 ⁄ 共 1876字 ⁄ 字号 评论关闭

开发环境jdk1.6,spring 3.0.2,spring tool suit。

1.新建一个java工程,在lib中加入如下jar包

2.写一个HelloWorld类,写一个sayHello()方法。

 

package com.mydomain

public class HelloWorld {
public
void sayHello(){
System.out.println(
"Hello World!");
}
}

3.类路径中创建bean配置文件bean.xml

 

 

代码

<?xml version="1.0" encoding="UTF-8"?>
<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"
>

<bean name="helloWorld" class="HelloWorld"></bean>

</beans>

4.写一个Main类测试HelloWorld.在这里用到用到接口ApplicationContext和ClassPathXmlApplicationContext。

 

 

代码

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
HelloWorld hello
= (HelloWorld)context.getBean("helloWorld");
hello.sayHello();
}

}

ApplicationContext是一个bean factory,可以存放各种bean和bean dependencies的注册。

 

ClassPathXmlApplicationContext是ApplicationContext的一个实现。

getBean(Stringname)取得配置的实例.然后调用方法sayHello().

5.运行程序。输出结果:

 

Hello World!

从控制台可以看到一些信息如下: 

 

 

代码

2010-6-5 21:51:55 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9:
 startup date [Sat Jun
05 21:51:55 CST 2010]; root of context hierarchy
2010-6-5 21:51:56 org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
信息: Loading XML bean definitions from
class path resource [bean.xml]
2010-6-5 21:51:57 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre
-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ef5502:
defining beans [helloWorld]; root of factory hierarchy
Hello World
!

 

 

抱歉!评论已关闭.