Spring-7-AOP

2019-10-04  本文已影响0人  宠辱不惊的咸鱼

概述

分类

概念

常用接口

方式

ProxyFactory

ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(new GreetingImpl());
proxyFactory.addAdvice(new GreetingBeforeAndAfterAdvice());
proxyFactory.addAdvice(new GreetingAroundAdvice());
Greeting greeting = (Greeting) proxyFactory.getProxy();
greeting.sayHello("Jack");

GreetingBeforeAndAfterAdvice implements MethodBeforeAdvice, AfterReturningAdvice
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    System.out.println("GreetingBeforeAndAfterAdvice: After");
}
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
    System.out.println("GreetingBeforeAndAfterAdvice: Before");
}

GreetingAroundAdvice implements MethodInterceptor
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    before();
    Object result = invocation.proceed();
    after();
    return result;
}

ProxyFactoryBean

aop-001.JPG
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="aAdvice" class="com.fjh.aop.AAdvice"></bean>
    <bean id="target" class="com.fjh.aop.Target"></bean>

    <bean id="ppp" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="proxyInterfaces">
            <value>com.fjh.aop.ITarget</value>
        </property>
        <property name="interceptorNames">
            <list>
                <value>aAdvice</value>
            </list>
        </property>
        <property name="target">
            <ref bean="target"/>
        </property>
    </bean>
</beans>
  1. 生成ppp
    1. 这里有个注意点,xml中配的接口是字符串,因为在ProxyFactoryBean中是Class<?> []类型,在IoC的populateBean过程中,有个convertForProperty的环节,把String加载生成Class对象,并作为数组元素
    2. initializeAdvisorChain
      1. 将aAdvice先裹成Advisor,塞到LinkedList<Advisor>
      2. 有适配器的影子:MethodBeforeAdviceAdapter
    3. 由DefaultAopProxyFactory获取AopProxy,可能是jdk,也可能是cglib;调用AopProxy.getProxy
      1. 配置了<aop:config proxy-target-class="true">或者没有接口,并且target本身不是接口,也不是被Proxy生成的代理类,那么采用cglib,否则采用jdk

疑问

xml中不配ITarget2,而Target实现2个接口,报错点在哪?

xml中配了ITarget2,而Target未实现ITarget2,报错点在哪?

上一篇 下一篇

猜你喜欢

热点阅读