且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring4-HelloWorld

更新时间:2022-10-05 08:28:45

1.创建项目,项目名称(springdemo1)

Spring4-HelloWorld


2.在项目目录中创建目录lib

Spring4-HelloWorld


3.在lib目录中创建jar包目录,分别对应的是apache,junit,spring这三个目录

Spring4-HelloWorld


4.分别在apache,junit,spring中添加jar包

Spring4-HelloWorld


5.对jar包进行build path,也就是添加jar包的引用

Spring4-HelloWorld


6.添加jar包后,会生成Referenced Libraries这个库,在程序中我们就可以使用到这些jar中提供的类文件

Spring4-HelloWorld


7.在项目中创建源码(src)和测试(test)目录

Spring4-HelloWorld


8.在src源码目录中右键创建HelloWorld类和包文件(main.java.com.mycompany.bean),操作如图所示

Spring4-HelloWorld

Spring4-HelloWorld

Spring4-HelloWorld


8.HelloWorld类文件中的代码如下:

package main.java.com.mycompany.bean;

/**
 * Bean
 * @author Administrator
 *
 */
public class HelloWorld {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	/*
	 * 输出信息
	 */
	public void printHello(){
		System.out.println("Spring 4 "+this.name);
	}
}


9.在源码目录src下创建applicationContext.xml配置文件,目录结构如下

Spring4-HelloWorld


10.applicationContext.xml中内容如下

<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">

	<!--
		id:取的是一个唯一标识名 
		class:对应的是HelloWorld的完整类名(包名+类名的组合)
		property:表示HelloWorld这个类中有一个属性叫name,并且对这个属性进行了赋值操作,值为yunshuo
	 -->
	<bean id="helloWorldBean" class="main.java.com.mycompany.bean.HelloWorld">
		<property name="name" value="yunshuo" />
	</bean>

</beans>


11.在test源码目录中创建测试类HelloWorldTest和包(main.java.com.mycompany.bean)

Spring4-HelloWorld


12.HelloWorldTest类中的内容如下

package main.java.com.mycompany.bean;


import main.java.com.mycompany.bean.HelloWorld;

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

public class HelloWorldTest {
	
	@Test
	public void helloWorldTest(){
		//获取配置文件上下文
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//通过上下文获取bean对象,并转换为具体的HelloWorld类
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorldBean");
		//调用HelloWorld类中的打印信息方法
		helloWorld.printHello();
	}
}


13.在helloWorldTest这个方法上右键运行,运行方式如下

Spring4-HelloWorld


14.在控制台输出Spring 4 yunshuo表示这个简单的spring应用完成.

Spring4-HelloWorld



本文转自 素颜猪 51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1908656

相关阅读