spring版本的经典入门" Hello world "

Spring初学者指南
本文详细介绍如何在Spring框架下创建第一个程序HelloWorld,包括环境搭建、类的定义、XML配置及运行结果展示,适合Spring框架初学者。

开始编写Spring的第一个程序HelloWorld
注意:

如果是使用MyEclipse进行开发的朋友可以直接右键需要导入Spring的项目–>ConConfigure Facet–>Install Spring Facet即可,不需要执行下面的(1)(2)步。

(1)下载STS(带有sts插件的Eclipse) 点击下载STS
(2)下载相关的JAR包( spring-framework-4.1.5.RELEASE-dist )    点击下载Spring包
         下载commons-logging-1.2 点我下载日志jar包

 

(3)把包导入到新建的Web项目中

    新建项目,添加一个lib文件,把刚才下载的包中的下面这些包拷贝进去,

右键`Build Path` ---〉`Add to Build Path`!
        

    新建下面3个文件
    HelloWorld.java
    Main.java
    applicationContext.xml
    这里写图片描述
    (三个文件的摆放位置如图所示,包名可以随便修改)

(4)编写相关类的代码

HelloWorld.java 代码:

package com.vow.spring;

public class HelloWorld {

	private String name;
	private int age;
	private String sex;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
}

applicationContext.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.xsd">
  <!-- 配置一个 bean --> 
  <bean id="helloWorld" class="com.vow.spring.HelloWorld" > 
    <!-- 为属性赋值 --> 
    <property name="name" value="vow"></property>
    <property name="age" value="18"> </property> 
    <property name="sex" value="男"> </property> 
   </bean>  
</beans>

Main.java

package com.vow.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
 public static void main(String[] args) {
	        //1. 创建 Spring 的 IOC 容器
			ClassPathXmlApplicationContext ctx =
					new ClassPathXmlApplicationContext("applicationContext.xml");
			//2. 从 IOC 容器中获取 bean 的实例
			HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
			//3. 使用 bean
			System.out.println(helloWorld.getName());
			System.out.println(helloWorld.getAge());
			System.out.println(helloWorld.getSex());
	}
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进朱者赤

多多支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值