-
@author 波波烤鸭
-
@email dengpbs@163.com
*/
public interface SomeService {
public void doSome();
}
/**
-
目标对象
-
@author 波波烤鸭
-
@email dengpbs@163.com
*/
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println(“目标对象…方法执行了”);
}
}
[](()3.创建通知/**
-
前置通知
-
需要实现MethodBeforeAdvice接口
-
@author 波波烤鸭
-
@email dengpbs@163.com
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
/**
-
method 目标方法
-
args 目标方法参数列表
-
target 目标对象
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(“前置通知执行了…”);
}
}
[](()4.配置文件xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:p=“http://www.springframework.org/schema/p” xmlns:context=“http://www.springframework.org/schema/context” xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> myMethodBeforeAdvice @Test public void test1() { ApplicationContext ac = new ClassPathXmlApplicationContext(“applicationContext.xml”); // 注意通过getBean获取增强的代理类!!! SomeService some = ac.getBean(“proxyFactoryBean”,SomeService.class); some.doSome(); } 输出: 说明我们配置的前置通知生效了,在目标方法执行之前执行了。 [](()二、适配器应用解析 说明: advice的类型有:BeforeAdvice,AfterReturningAdvice,ThrowsAdvice等 每个类型的通知都有对应的拦截器 | advice | 拦截器 | | — | :-- | | BeforeAdvice | MethodBeforeAdviceInterceptor | | AfterAdvice | AfterReturningAdviceInterceptor | | AfterAdvice | ThrowsAdviceInterceptor | 以前置通知为例 MethodBeforeAdvice public interface 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 MethodBeforeAdvice extends BeforeAdvice { void before(Method method, Object[] args, Object target) throws Throwable; } Adapter的接口 AdvisorAdapter public interface AdvisorAdapter { // 判断通知类型是否匹配 boolean supportsAdvice(Advice advice); // 获取对应的拦截器 MethodInterceptor getInterceptor(Advisor advisor); } MethodBeforeAdviceAdapter class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable { @Override public boolean supportsAdvice(Advice advice) { return (advice instanceof MethodBeforeAdvice); } @Override public MethodInterceptor getInterceptor(Advisor advisor) { MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice(); // 通知类型匹配对应的拦截器 return new MethodBeforeAdviceInterceptor(advice); } } 代理类通过DefaultAdvisorAdapterRegistry类来注册相应的适配器。 public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable { private final List adapters = new ArrayList(3); /** */ public DefaultAdvisorAdapterRegistry() { 欢迎分享,转载请注明来源:内存溢出
[](()1.Advice体系结构
[](()2.适配器的实现
评论列表(0条)