Spring4之Helloworld

 

工具和环境:

-----------------------------------------------------------------------------

Eclipse版本:eclipse-jee-luna-R-win32

JDK版本:jdk1.7.0_21

Spring版本:spring-framework-4.0.0.RELEASE-dist

 

步骤:

-----------------------------------------------------------------------------

1. 新建Java工程

 

2. 把以下 jar 包加入到工程的 classpath 下:

 

    2.1 spring包:

          spring-framework-4.0.0.RELEASE-dist:

          spring-beans-4.0.0.RELEASE.jar

          spring-context-4.0.0.RELEASE.jar

          spring-core-4.0.0.RELEASE.jar

          spring-expression-4.0.0.RELEASE.jar

   

    2.2 commons包:

          commons-logging-1.1.1.jar

 

3. 添加类Helloworld

 

package xyz.huning.spring4.helloworld;
public class Helloworld {
	private String username;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void say() {
		System.out.println("hello: " + this.username);
	}
}

 

 4. 添加Spring 的配置文件(一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件, 这些配置文件用于在 Spring IOC 容器里配置 Bean. Bean 的配置文件可以放在 classpath 下, 也可以放在其它目录下。)

 

<?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="xyz.huning.spring4.helloworld.Helloworld">
		<!-- 为属性赋值 -->
		<property name="username" value="Rabbit"></property>
	</bean>
</beans>

 

 5. 添加测试类Main

 

package xyz.huning.spring4.helloworld;

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

public class Main {
	public static void main(String[] args) {
		// 1. 创建Spring的IOC容器
		// ApplicationContext代表IOC容器
		// ClassPathXmlApplicationContext:从 类路径下加载配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
		// 2. 从IOC容器中获取bean
		Helloworld helloworld = context.getBean("helloWorld", Helloworld.class);
		helloworld.say();
		
		((ClassPathXmlApplicationContext)context).close();
	}
}

 

6. 执行测试类的main方法




 
 

猜你喜欢

转载自ihuning.iteye.com/blog/2223546
今日推荐