Inside-springframework-AOP-invoke

来源:互联网 发布:5g网络是什么意思 编辑:程序博客网 时间:2024/05/29 15:11
 

Inside-springframework-AOP-invoke

 

 

 

      开场

/*****************段落1********************/

      public class ViewCategoryAction extends BaseAction {

 

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

UserManager mgr = (UserManager) getBean("userManager"); (1)段落1

 

List users = mgr.getAllUsers(); 7)段落2

}

public Object getBean(String name) { 1注)

      ApplicationContext ctx =        

WebApplicationContextUtils.getRequiredWebApplicationContext(

servlet.getServletContext()); (2)

 

    return ctx.getBean(name); 4

  }

}

 

      public abstract class WebApplicationContextUtils {

public static WebApplicationContext

getRequiredWebApplicationContext(ServletContext sc) 2注)

    throws IllegalStateException {

     WebApplicationContext wac = getWebApplicationContext(sc); (3)

     return wac;

}

 

//3注):从servletContext中取得WebApplicationContext

public static WebApplicationContext getWebApplicationContext(ServletContext sc) {

     Object attr = sc.getAttribute(

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 

        return (WebApplicationContext) attr;

}

}

 

public abstract class AbstractApplicationContext extends DefaultResourceLoader

        implements ConfigurableApplicationContext, DisposableBean {

    public Object getBean(String name) throws BeansException { (4)

        return getBeanFactory().getBean(name);(5)

    }

}

 

      public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {

 

return this.beanFactory;

}

 

      public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

public Object getBean(String name, Class requiredType, final Object[] args)

throws BeansException { (5)

//example: beanName=userManager

     final String beanName = transformedBeanName(name);

     Object bean = null;

     //实际返回的是JdkDynamicAopProxy对象

     //原因请参加Inside-springframework-AOP-creator

     Object sharedInstance = getSingleton(beanName);6

 

     if (containsBeanDefinition(beanName)) {

         RootBeanDefinition mergedBeanDefinition =

getMergedBeanDefinition(beanName, false);

         bean = getObjectForBeanInstance(sharedInstance, name,

mergedBeanDefinition);

     }

     return bean;

}

}

 

public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    public Object getSingleton(String beanName) { (6)

        synchronized (this.singletonCache) {

            return this.singletonCache.get(beanName);

        }

    }

 

}

☆ 初识容颜

/*****************段落2 mgr.getAllUsers()********************/

此时的mgr指向的是一个JdkDynamicAopProxy对象,因此调用mgr.getAllUsers()

实际调用如下:

//参数分别为:proxyJdkDynamicAopProxy

// method= UserManager.getAllUsers()

final class JdkDynamicAopProxy implements AopProxy,

InvocationHandler, Serializable {

    public Object invoke(Object proxy, Method method, Object[]

args) throws Throwable {

        MethodInvocation invocation = null;

        Object oldProxy = null;

        boolean setProxyContext = false;

 

        // targetSource =UserManagerImpl:被代理对象

        TargetSource targetSource =

this.advised.targetSource;

 

        … …

        target = targetSource.getTarget();

        // targetClass =UserManagerImpl

        targetClass = target.getClass();

 

        //chain=OSCacheInterceptor

List chain =  

this.advised.advisorChainFactory.

getInterceptorsAndDynamicInterceptionAdvice(

                this.advised, proxy, method, targetClass);(1)

 

        2

        //invocation=invocation: method 'getAllUsers',

//arguments []; target is of class

//[org.springframework.samples.jpetstore.service.

//UserManagerImpl]

        invocation = new ReflectiveMethodInvocation(

        proxy, target, method, args, targetClass, chain);

        //调用Interceptor. invoke(MethodInvocation invocation)

        retVal = invocation.proceed();3

    }

}

 

      public final class HashMapCachingAdvisorChainFactory implements AdvisorChainFactory {

public List

getInterceptorsAndDynamicInterceptionAdvice(

         Advised config, Object proxy, Method method, Class

targetClass) { (1)

            //cached= OSCacheInterceptor (自定义的Interceptor)

            List cached = (List) this.methodCache.get(method);

            return cached;

    }

}

      public class ReflectiveMethodInvocation implements

ProxyMethodInvocation, Cloneable {

     (2)

     public ReflectiveMethodInvocation(

    Object proxy, Object target, Method method, Object[]

arguments,Class targetClass, List

interceptorsAndDynamicMethodMatchers) {

 

     this.proxy = proxy;

     this.target = target;

     this.targetClass = targetClass;

     this.method = method;

     this.arguments = arguments;

     this.interceptorsAndDynamicMethodMatchers =

interceptorsAndDynamicMethodMatchers;

}

 

34注)

protected Object invokeJoinpoint() throws Throwable {

     return

AopUtils.invokeJoinpointUsingReflection(this.

target, this.method, this.arguments); 35

}

(3)

public Object proceed() throws Throwable {

     if (this.currentInterceptorIndex ==

this.interceptorsAndDynamicMethodMatchers.size() - 1) {

         return invokeJoinpoint();34

     }

     // interceptorOrInterceptionAdvice=

     //OSCacheInterceptor

     Object interceptorOrInterceptionAdvice =

         this.interceptorsAndDynamicMethodMatchers.get

(++this.currentInterceptorIndex);

 

        … …

        (4)段落3

        return ((MethodInterceptor)

interceptorOrInterceptionAdvice).invoke(this);

}

}

35注)

// target为被代理对象,这里为UserManagerImpl

// method为调用方法,这里为getAllUsers()

public abstract class AopUtils {

        public static Object invokeJoinpointUsingReflection

(Object target, Method method, Object[] args)

             throws Throwable {

        if (!Modifier.isPublic(method.getModifiers()) ||

                !Modifier.isPublic(method.getDeclaringClass().

getModifiers())) {

                method.setAccessible(true);

            }

            // method= public abstract java.util.List

            //  org.springframework.samples.jpetstore.

//service.UserManager.getAllUsers()

//方法被代理对象方法的执行结果

            return method.invoke(target, args);

    }

}

☆ 渐入佳境

/********段落3 Interceptor. invoke(MethodInvocation invocation)********/

Note:这一段为用户自定义的Interceptor实现类,该类必须实现invoke(MethodInvocation invocation)方法

这里OSCacheInterceptor继承自CacheInterceptor

      public abstract class CacheInterceptor implements MethodInterceptor, InitializingBean,

ApplicationListener {

     //将代理对象JdkDynamicAopProxy包装为

//org.aopalliance.intercept.MethodInvocation

//然后传给Interceptor处理

     public Object invoke(MethodInvocation invocation) throws Throwable {

//example:cacheName= //org.springframework.samples.jpetstore.

//service.UserManager@getAllUsers

         String cacheName = getCacheName(invocation);1

         String key = getCacheKey(invocation.getThis(),(2)

invocation.getArguments(),invocation.getMethod().getParameterTypes())  

            //调用代理方法

            Object result = getFromCache(cacheName,key);

            if (result == null) {

                //被代理对象的方法、这里为UserManager#getAllUsers()

                33)又绕回ReflectiveMethodInvocation去了,注释在上

                这里是在调用被代理对象的方法

                result = invocation.proceed(); 

                putInCache(cacheName,key,result);

          }

     }

     (1)

     protected String getCacheName(MethodInvocation invocation) {

        return invocation.getMethod().getDeclaringClass().getName()

              + "@" + invocation.getMethod().getName();

    }

   (2)

     protected String getCacheKey(Object target, Object[] arguments, Class[]

argumentClasses) throws CacheInterceptorException {

            StringBuffer result = new StringBuffer();

            … …

            //example: result= 4b4b50@

            result.append(this.objectDiscriminator);

            return result.toString();

        }

}

 

 

 

 

 

 

 

 

 

原创粉丝点击