首先,我们声明一个接口:Performer,演员具有表演的能力
package com;
import com.exception.PerformanceExcetion;
public interface Performer {
void perform() throws PerformanceExcetion;
}
然后,让一个杂技师继承演员的接口,并实现:
package com.entity;
import com.Performer;
import com.exception.PerformanceExcetion;
public class Juggler implements Performer{
private int beanBags=3;
public Juggler(){
}
public Juggler (int beanBags){
this.beanBags=beanBags;
}
@Override
public void perform() throws PerformanceExcetion {
System.out.println("Juggler(杂技师) "+ beanBags +" beanBags ");
}
}
然后我们在声明一个接口:竞争者,有一个奖励现金的方法:
package com.entity;
public interface Contestant {
public void receiveAward();
}
我们写一个他的实现类,每一个竞争者都给予现金奖励:package com.entity;
public class ContestantImpl implements Contestant{
public void receiveAward() {
System.out.println("给予现金五千万");
}
}
package com.entity;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
@Aspect
public class ContestantIntroducer {
//value:被引入指定接口的Bean类型,defaultImpl:提供了所引入接口的实现
//@DeclareParents:指定了将被引入的接口
@DeclareParents(value="com.entity.Juggler+",defaultImpl=ContestantImpl.class)
public static Contestant contestant;
}
我们可以看到,vaule指定了要被引入的接口的实现类,defaultImpl:引入的接口实现类
在配置文件中声明这个两个Bean:
<aop:aspectj-autoproxy/>
<bean id="juggler" class="com.entity.Juggler"></bean>
<bean id="ContestantIntroducer" class="com.entity.ContestantIntroducer"></bean>
<bean id="ContestantImpl" class="com.entity.ContestantImpl"></bean>
测试类:
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.entity.Contestant;
import com.entity.ContestantImpl;
import com.entity.ContestantIntroducer;
import com.entity.Juggler;
import com.entity.Thinker;
public class springTest {
public static void main(String[] args) {
ApplicationContext cxt=new ClassPathXmlApplicationContext(
"classpath:/spring/spring.xml");
Performer performer =(Performer)cxt.getBean("juggler");
performer.perform();
Contestant contestant =(Contestant)cxt.getBean("juggler");
contestant.receiveAward();
}
}
我们可以看到,获取同一个Bean杂技师,转换成不同的两个Bean,具有两个方法,那么此时杂技师就既是一名表演者,又是一名竞争者
输出:
Juggler(杂技师) 3 beanBags
给予现金五千万