[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="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://www.springframework.org/schema/beans" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 配置KnifeWeapon实例,其实现类是KnifeWeapon --> <bean > <!-- 将GunWeapon注入给weapon属性 --> <property name="weapon" ref="KnifeWeapon"/> </bean> <!-- 配置GunWeapon实例,其实现类是GunWeapon --> <bean /> <!-- 配置KnifeWeapon实例,其实现类是KnifeWeapon --> <bean /> </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
最后更新:2017-04-04 07:03:36