Spring源码详解

AOP

相关文章:https://blog.csdn.net/wyl6019/article/details/80136000

XML注册

70

@Aspect注册

71

  • contextInitialized:103, ContextLoaderListener
  • initWebApplicationContext:291, ContextLoader
  • configureAndRefreshWebApplicationContext:400, ContextLoader
  • refresh:549, AbstractApplicationContext
  • finishBeanFactoryInitialization:877, AbstractApplicationContext
  • preInstantiateSingletons:830, DefaultListableBeanFactory
  • getBean:199, AbstractBeanFactory
  • doGetBean:318, AbstractBeanFactory
  • getSingleton:222, DefaultSingletonBeanRegistry
  • getObject:-1, 889007824
  • lambda$doGetBean$0:320, AbstractBeanFactory
  • createBean:515, AbstractAutowireCapableBeanFactory
  • doCreateBean:593, AbstractAutowireCapableBeanFactory
  • initializeBean:1766, AbstractAutowireCapableBeanFactory
  • applyBeanPostProcessorsAfterInitialization:429, AbstractAutowireCapableBeanFactory
  • postProcessAfterInitialization:296, AbstractAutoProxyCreator
  • wrapIfNecessary:335, AbstractAutoProxyCreator
  • createProxy:471, AbstractAutoProxyCreator
  • createProxy:471, AbstractAutoProxyCreator
  • getProxy:160, CglibAopProxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}

try {
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

Class<?> proxySuperClass = rootClass;
if (ClassUtils.isCglibProxyClass(rootClass)) {
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}

// Validate the class, writing log messages as necessary.
validateClassIfNecessary(proxySuperClass, classLoader);

// Configure CGLIB Enhancer...
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
// 获取Callback派生类,包含@After、@Before等
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);

// Generate the proxy class and create a proxy instance.
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
1
2
3
4
5
6
7
8
9
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}

执行

  • intercept:688, CglibAopProxy$DynamicAdvisedInterceptor
  • proceed:162, ReflectiveMethodInvocation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}

Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
// 调用机制相当于实现了一个chain,把this传给下一个Callback,注意获取的时候++this.currentInterceptorIndex
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}

处理请求

注册

  • refresh:549, AbstractApplicationContext
  • finishBeanFactoryInitialization:877, AbstractApplicationContext
  • preInstantiateSingletons:849, DefaultListableBeanFactory
  • getBean:199, AbstractBeanFactory
  • doGetBean:318, AbstractBeanFactory
  • getSingleton:222, DefaultSingletonBeanRegistry
  • getObject:-1, 911637678
  • lambda$doGetBean$0:320, AbstractBeanFactory
  • createBean:515, AbstractAutowireCapableBeanFactory
  • doCreateBean:593, AbstractAutowireCapableBeanFactory
  • initializeBean:1758, AbstractAutowireCapableBeanFactory
  • invokeInitMethods:1821, AbstractAutowireCapableBeanFactory
  • afterPropertiesSet:164, RequestMappingHandlerMapping
  • afterPropertiesSet:199, AbstractHandlerMethodMapping
  • initHandlerMethods:211, AbstractHandlerMethodMapping

getCandidateBeanNames()获取到需要初始化的bean,processCandidateBean(beanName)方法对这些bean进行过滤

1
2
3
4
5
6
7
8
protected void initHandlerMethods() {
for (String beanName : getCandidateBeanNames()) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
processCandidateBean(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}
  • processCandidateBean:250, AbstractHandlerMethodMapping

    isHandler(beanType)主要过滤条件,detectHandlerMethods(beanName);注册

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    protected void processCandidateBean(String beanName) {
    Class<?> beanType = null;
    try {
    beanType = obtainApplicationContext().getType(beanName);
    }
    catch (Throwable ex) {
    // An unresolvable bean type, probably from a lazy bean - let's ignore it.
    if (logger.isTraceEnabled()) {
    logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
    }
    }
    if (beanType != null && isHandler(beanType)) {
    detectHandlerMethods(beanName);
    }
    }

    符合@Controller或者@RequestMapping

    1
    2
    3
    4
    protected boolean isHandler(Class<?> beanType) {
    return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
    AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
    }

请求

  • org.springframework.web.servlet.DispatcherServlet
  • service:882, FrameworkServlet
  • service:742, HttpServlet
  • service:635, HttpServlet

    这个方法具体判断是什么请求类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
    long lastModified = getLastModified(req);
    if (lastModified == -1) {
    // servlet doesn't support if-modified-since, no reason
    // to go through further expensive logic
    doGet(req, resp);
    } else {
    long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
    if (ifModifiedSince < lastModified) {
    // If the servlet mod time is later, call doGet()
    // Round down to the nearest second for a proper compare
    // A ifModifiedSince of -1 will always be less
    maybeSetLastModified(resp, lastModified);
    doGet(req, resp);
    } else {
    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }
    }

    } else if (method.equals(METHOD_HEAD)) {
    long lastModified = getLastModified(req);
    maybeSetLastModified(resp, lastModified);
    doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
    doPost(req, resp);

    } else if (method.equals(METHOD_PUT)) {
    doPut(req, resp);

    } else if (method.equals(METHOD_DELETE)) {
    doDelete(req, resp);

    } else if (method.equals(METHOD_OPTIONS)) {
    doOptions(req,resp);

    } else if (method.equals(METHOD_TRACE)) {
    doTrace(req,resp);

    } else {
    //
    // Note that this means NO servlet supports whatever
    // method was requested, anywhere on this server.
    //

    String errMsg = lStrings.getString("http.method_not_implemented");
    Object[] errArgs = new Object[1];
    errArgs[0] = method;
    errMsg = MessageFormat.format(errMsg, errArgs);

    resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
    }
  • doGet:897, FrameworkServlet
  • processRequest:1005, FrameworkServlet
  • doService:942, DispatcherServlet
  • doDispatch:1014, DispatcherServlet
  • getHandler:1231, DispatcherServlet
  • getHandler:401, AbstractHandlerMapping
  • getHandlerInternal:365, AbstractHandlerMethodMapping

    AbstractHandlerMethodMapping内部使用了读写锁

    lookupHandlerMethod(lookupPath, request); 从注册好的集合中查找返回HandlerMethod调用

    mappingRegistry.urlLookup这个map保存了url和对应的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
    this.mappingRegistry.acquireReadLock();
    try {
    HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
    return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
    }
    finally {
    this.mappingRegistry.releaseReadLock();
    }
    }

事务

Spring并不直接管理事务,而是提供了事务管理接口是PlatformTransactionManager,通过这个 接口,Spring 为各个平台如JDBC、Hibernate等都提供了对应的事务管理器,但是具体的实现就是各个平台自己的 事情了。

平台 实现类
JDBC DataSourceTransactionManager
JTA JtaTransactionManager
Hibernate HibernateTransactionManager

注册

执行