众所周知,任何程序的起步都是从Hello World开始,
今天我们就用Spring来做个Hello World程序。
首先,我们要做个class,这个class是一个简单的JavaBean,我们
用它来存放业务关键字,简称它为HelloBean。
代码如下:
接下来,我们的任务便是要做一个Spring的配置文件,这个文件的主要作用
在于:存放我们刚才建立的JavaBean,也就是HelloBean。
文件的格式为xml,文件名无所谓可以任意,我们取名为: hello-config.xml。
代码如下:
最后,我们要编写客户端程序来从xml文件中读取Bean并且把它显示在界面上。
基本方法有2种:
[b][color=blue]
1) 工厂类读取(BeanFactory)
2) Spring上下文读取(ApplicationContext)
[/color][/b]
BeanFactory代码如下:
ApplicationContext代码如下:
今天我们就用Spring来做个Hello World程序。
首先,我们要做个class,这个class是一个简单的JavaBean,我们
用它来存放业务关键字,简称它为HelloBean。
代码如下:
package spring.basic.hello;
public class HelloBean {
private String helloWord;
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
}
接下来,我们的任务便是要做一个Spring的配置文件,这个文件的主要作用
在于:存放我们刚才建立的JavaBean,也就是HelloBean。
文件的格式为xml,文件名无所谓可以任意,我们取名为: hello-config.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-2.0.xsd">
<bean id="helloBean"
class="spring.basic.hello.HelloBean">
<property name="helloWord" value="Hello David!" />
</bean>
</beans>
最后,我们要编写客户端程序来从xml文件中读取Bean并且把它显示在界面上。
基本方法有2种:
[b][color=blue]
1) 工厂类读取(BeanFactory)
2) Spring上下文读取(ApplicationContext)
[/color][/b]
BeanFactory代码如下:
package spring.basic.hello;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class SpringDemo {
public static void main(String[] args) throws Exception {
BeanFactory factory = getBeanFactory();
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
private static BeanFactory getBeanFactory() throws Exception {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
"hello-config.xml"));
return factory;
}
}
ApplicationContext代码如下:
package spring.basic.hello;
import spring.basic.hello.HelloBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemoContext {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"hello-config.xml");
HelloBean hello = (HelloBean) context.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
本文介绍了使用Spring框架实现简单的HelloWorld程序的过程。包括创建JavaBean、配置Spring XML文件及通过BeanFactory或ApplicationContext读取Bean并输出。
1235

被折叠的 条评论
为什么被折叠?



