前言
一个很常规的需求,目标是为服务接口的实现类定义切面来解耦某些与业务无关的操作。期间突然萌生了一个想法:我们知道spring-aop在被通知类拥有的接口的情况下默认采用JDK动态代理模式来织入切面的,而JDK动态代理只会对接口中定义的方法进行拦截,那么被代理中自定义的方法在调用时会发生什么行为呢?
被代理类的接口
package com.special.learningspring.aspect;
public interface Performance {
String perform();
}
接口实现类
package com.special.learningspring.aspect;
import com.special.learningspring.aspect.Performance;
import org.springframework.stereotype.Component;
/**
* Created by Special on 2018/6/12 17:51
*/
@Component
public class ImplementsPer implements Performance{
public String perform() {
String str = "2323";
return str + "0000";
}
public String myPerform() {
return "my sucess";
}
}
切面
package com.special.learningspring.aspect;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* Created by Special on 2018/6/12 11:52
*/
@Aspect
@Component
public class Audience {
//Pointcut定义可重用的切点
@Pointcut("execution (* com.special.learningspring.aspect.ImplementsPer.perform(..))")
public void performance() {}
@Before("performance()")
public void silenceCellPhones() {
System.out.println("Silence cell phones");
}
}
测试类
import com.special.learningspring.aspect.ImplementsPer;
import com.special.learningspring.aspect.Performance;
import com.special.learningspring.config.PerformanceConfig;
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;
/**
* Created by Special on 2018/6/10 15:13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PerformanceConfig.class)
public class AspectXMLTest {
@Autowired
ImplementsPer implementsPer;
@Test
public void test() {
System.out.println(implementsPer.perform());
}
}
报错
D:\program-model-path\jdk1.8\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\software\IDEAProfessional\IntelliJ IDEA 2018.1.6\lib\idea_rt.jar=49825:D:\software\IDEAProfessional\IntelliJ IDEA 2018.1.6\bin" -Dfile.encoding=UTF-8 -classpath "D:\software\IDEAProfessional\IntelliJ IDEA 2018.1.6\lib\idea_rt.jar