首先,我們聲明一個接口: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
給予現金五千萬