Spring 引入式AOP 实例
package cn.com.chujie.spring.springAop;
public interface Performance {
public void perform();
}
package cn.com.chujie.spring.springAop;
import org.springframework.stereotype.Component;
@Component
public class PerformanceImpl implements Performance {
@Override
public void perform() {
System.out.println("PerformanceImpl.perform()执行");
}
}
package cn.com.chujie.spring.springAop;
public interface Encoreable {
void performEncore();
}
package cn.com.chujie.spring.springAop;
public class DefaultEncoreable implements Encoreable {
@Override
public void performEncore() {
System.out.println("DefaultEncoreable.performEncore()");
}
}
package cn.com.chujie.spring.springAop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
/**
* 引入式AOP
*/
@Aspect
public class EncoreableIntroducer {
@DeclareParents( value = "cn.com.chujie.spring.springAop.Performance+",
defaultImpl = DefaultEncoreable.class )
public static Encoreable encoreable;
}
package cn.com.chujie.spring.springAop;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mvc.xml" , "classpath:spring-aop.xml","classpath:spring-bean.xml"})
public class AopTest {
@Autowired
Performance performanceImpl;
@Test
public void audience(){
Assert.assertNotNull(performanceImpl);
performanceImpl.perform();
Encoreable encoreable = (Encoreable)performanceImpl;
encoreable.performEncore();
}
}