您的位置:首页 > 编程语言 > Java开发

Java Spring的配置以及第一个HelloWorld

2014-10-23 19:24 387 查看
第一个spring程序的配置以及过程中遇到的问题:

1.首先你的Eclipse已经配置好

2. 首先是Spring-tool-suite的安装(我的版本是springsource-tool-suite-

3.6.2.RELEASE-e3.8.2-updatesite.zip稍后会给出网盘链接)

2.1 首先 help--->Install New Software--->Add添加你的spring-tool-suite(此时

会在中间的列表框中进行选择, 你只需要选择Spring-IDE结尾的所有选项)--->在下面

的单选列表中将Contact all那个去掉,防止在线更新---->点击下一步,下一步即可

最后在Perferences中看见你的Spring, 基本上你的就安装完成了

3.此时导入Spring所以依赖的包

commons-logging-1.1.3.jar

spring-beans-4.0.5.RELEASE.jar

spring-context-4.0.5.RELEASE.jar

spring-core-4.0.5.RELEASE.jar

spring-expression-4.0.5.RELEASE.jar

下载链接后面会给出来

4.现在我们写一个简单的HelloWorld程序

HelloWorld.java

public class HelloWorld {

private String name;

public HelloWorld() {

System.out.println("This is a constructor function");

}

public String getName(){

return "Hello: "+name;

}

public void setName(String name){ //这里定义成public方法

this.name = name;

}

}

Main.java

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

//HelloWorld he = new HelloWorld();

//he.setString("Jack");

//System.out.println(he.getString());

//调用spring方法

//1. 创建spring的IOC 容器对象

ApplicationContext act = new ClassPathXmlApplicationContext

("Application.xml");

//2. 从IOC容器中获取Bean实例

HelloWorld he = (HelloWorld)act.getBean("helloWorld");

//3. 调用方法

System.out.println(he.getName());

}

}

这是在当前文件夹下建立的xml配置文件

Application.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="SMI.HelloWorld">

<!-- <property name="name" value="Jack"></property> -->

<property name="name" value="Jack"></property> <!-- 这里的

name代表的setName方法 切记 -->

</bean>

</beans>

好了,一个简单的基于Spring的HelloWorld程序就建成了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: