SpringAOP的引入通过@DeclareParents
实现,其目标是对于一个已有的类引入新的接口。
//业务接口类
package com.codestd.springstudy.aop.introductions;
public interface Animal {
public void sleep();
public void shout();
}
//-----------------------------------------
//实现类
package com.codestd.springstudy.aop.introductions;
import org.springframework.stereotype.Component;
@Component
public class Cock implements Animal {
@Override
public void sleep() {
System.out.println("Cock sleep");
}
@Override
public void shout() {
System.out.println("Cock shout");
}
}
//-----------------------------------------
//要引入的接口
package com.codestd.springstudy.aop.introductions;
public interface Flyable {
public void fly();
}
//-----------------------------------------
//引入接口的实现类
package com.codestd.springstudy.aop.introductions;
public class DefaultFlyable implements Flyable {
@Override
public void fly() {
System.out.println("fly");
}
}
//-----------------------------------------
//声明引入
package com.codestd.springstudy.aop.introductions;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AnimalIntroduction {
@DeclareParents(value="com.codestd.springstudy.aop.introductions.Animal+", defaultImpl=DefaultFlyable.class)
public static Flyable flyable;
}
现在就可以认为Animal的实现类同时也实现了Flyable接口。然后可以直接从Spring容器中获取Bean,然后调用接口内的方法。接口的方法是defaultImpl
中指定的实现类中方法的实现。
//-----------------------------------------
//测试,现在可以直接通过Spring获取到实现
package com.codestd.springstudy.aop.introductions;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:aop/applicationContext.xml"})
public class AnimalTest {
@Resource(name="cock")
private Flyable flyable;
@Test
public void test() {
this.flyable.fly();
}
}