Spring简单实例

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();
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值