1. 下载Spring库文件
commons-logging-1.2.jar
spring-beans-3.2.8.RELEASE.jar
spring-context-3.2.8.RELEASE.jar
spring-core-3.2.8.RELEASE.jar
spring-expression-3.2.8.RELEASE.jar
2. 简单实例
2.1 基本类
public interface Weapon {
void fire();
}
public class HandGun implements Weapon {
public void fire() {
System.out.println("手枪开火");
}
}
public class MachineGun implements Weapon {
public void fire() {
System.out.println("机枪开火");
}
}
public class Soldier {
private String name;
private Weapon weapon;
// 构造注入
public Soldier(String name) {
this.name = name;
}
public String getName() {
return name;
}
// setter 注入
public void setName(String name) {
this.name = name;
}
public Weapon getWeapon() {
return weapon;
}
// Weap对象实例化由Spring控制(IOC),对象由Spring注入(DI)
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
// 依赖性强
// 使用 IOC (Inversion Of Control) 和 DI (Dependence Inject)
/*
public void fire() {
HandGun handGun = new HandGun();
handGun.fire();
}
*/
public void fire() {
this.weapon.fire();
}
}
2.2 Spring配置
<?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-2.5.xsd">
<!-- 1. scope="", 默认是singleton,为单例对象 -->
<!-- 2. scope="prototype" 或 "singleton=false", 每次请求都创建一个新的对象 -->
<bean id="soldier" class="test2.Soldier" scope="prototype">
<!-- 构造注入 -->
<constructor-arg value="RANBO"></constructor-arg>
<!-- setter 注入 -->
<!-- <property name="name" value="RANBO"></property> -->
<property name="weapon">
<!-- 依赖注入 (DI) -->
<ref bean="machineGun"></ref>
</property>
</bean>
<bean id="handGun" class="test2.HandGun" scope="prototype"></bean>
<bean id="machineGun" class="test2.MachineGun" scope="prototype"></bean>
</beans>
2.3 测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String args[]) {
// 初始化Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("test2/applicationContext.xml");
// 从Spring容器中取得对象
Soldier soldier = (Soldier) context.getBean("soldier");
System.out.println(soldier.getName());
soldier.fire();
}
}