第一篇Hello World

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架

按照国际惯例,开篇就是Hello Wold

 第一步导入spring的jar包

spring-core-4.2.1.RELEASE.jar
commons-logging-1.2.jar
spring-context-4.2.1.RELEASE.jar
spring-aop-4.2.1.RELEASE.jar
aopalliance-1.0.jar
spring-expression-4.2.1.RELEASE.jar
spring-context-support-4.2.1.RELEASE.jar
spring-beans-4.2.1.RELEASE.jar
junit-3.8.1.jar

第二步编写HelloWorld.java的bean

package com.hous.spring;

public class HelloWorld {
	private String name;

	/**
	 * 这个是必须的,spring容器通过这个方法给name赋值
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	public void hello() {
		System.out.println("Hello " + name);
	}
	
}

第三步编写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.hous.spring.HelloWorld">
		<property name="name" value="shanshanbox.com"></property>
	</bean>
	
</beans>

 第四步编写测试类Test.java

package com.hous.test;

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

import com.hous.spring.HelloWorld;

public class Test {
	public static void main(String[] args) {
		//1.创建spring的IoC容器
		ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IoC容器中获取bean
		HelloWorld helloWorld = (HelloWorld) cxt.getBean("helloWorld");
		//3.调用hello方法
		helloWorld.hello();
	}
}

不好意思,改了个惯例。如果照抄上面的代码,你会打印出【Hello shanshanbox.com

这个是在applicationContext.xml配置文件中设置的,可以改

猜你喜欢

转载自shuizhongyue.iteye.com/blog/2290328