第一个Spring应用程序 - Hello World

众所周知,任何程序的起步都是从Hello World开始,
今天我们就用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());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值