[Spring]有一个人的类,他有使用武器的方法;有英雄类,继承人的类;武器有手枪和武士刀。

这道题是我自己出的给自己做的,练习spring,使用setter注入,面向接口编程,我的程序如下:


在com.zzk.app.service包下

package com.zzk.app.service;

public interface Person {
	//定义一个使用武器的方法
    public void useWeapon();
}



package com.zzk.app.service;

public interface Weapon {
    //Weapon接口里有一个攻击的方法
	public String attack();
}

在com.zzk.app.service.impl包内


package com.zzk.app.service.impl;

import com.zzk.app.service.Person;
import com.zzk.app.service.Weapon;

public class Hero implements Person{

	private Weapon weapon;
	//设值注入所需的setter方法

	public void setWeapon(Weapon weapon) {
		this.weapon = weapon;
	}
	
   //实现Person接口的useWeapon方法
	public void useWeapon() {
		//调用weapon的attack()方法,
		//表明Person对象依赖于axe对象
		System.out.println(weapon.attack());
	}

}


package com.zzk.app.service.impl;

import com.zzk.app.service.Weapon;

public class GunWeapon implements Weapon{

	public String attack() {
		return "AK47,秒杀你";
	}

}


package com.zzk.app.service.impl;

import com.zzk.app.service.Weapon;

public class GunWeapon implements Weapon{

	public String attack() {
		return "AK47,秒杀你";
	}

}


bean.xml

<?xml version="1.0" encoding="GBK"?>
<!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<!-- 配置KnifeWeapon实例,其实现类是KnifeWeapon -->
	<bean id="Hero" class="com.zzk.app.service.impl.Hero">
		<!-- 将GunWeapon注入给weapon属性 -->
		<property name="weapon" ref="KnifeWeapon"/>
	</bean>
	<!-- 配置GunWeapon实例,其实现类是GunWeapon -->
	<bean id="GunWeapon" class="com.zzk.app.service.impl.GunWeapon"/>
	<!-- 配置KnifeWeapon实例,其实现类是KnifeWeapon -->
	<bean id="KnifeWeapon" class="com.zzk.app.service.impl.KnifeWeapon"/>
</beans>


在com.zzk.app.test包下

package com.zzk.app.test;

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

import com.zzk.app.service.Person;

public class BeanTest {
    public static void main(String[] args) {
		//创建Spring容器
    	ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
    	//获取Hero实例
    	Person p = (Person)ctx.getBean("Hero", Person.class);
    	p.useWeapon();
    }
}

over




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值