“AOP代理”遇到“双上下文”

最近有小伙伴儿遇到了一个问题来咨询我,问题大致如下:

他在Service层利用Aspect设置了一个Spring AOP代理,在单元测试以及在service层代码上添加代理的时候均没有发现问题,但是在web服务中的controller层代码添加代理的时候却不成功。

其代码大概如下:

@Component
public class CoreBusiness {
     public void doSomething() {
         System.out.println("I did something");
     }     
}

@Controller
public class CoreController {
     public void doSomething() {
         System.out.println("I did something");
     }     
}

@Component
@Aspect
public class CrossCuttingConcern {
      @Before("execution(* com.test.CoreBusiness.*(..)) || execution(* com.test.CoreController.*(..))")
       public void doCrossCutStuff(){
              System.out.println("Doing the cross cutting concern now");
        }
}

同时在Service层有如下的配置:

<aop:aspectj-autoproxy expose-proxy="true"/>

其实要弄清楚这个问题需要明白两点:

1、双上下文的概念

2、AOP Proxy的创建机制

我们先来看看什么情况下我们会用到双上下文

场景1:

现在假设我们有一个客户端程序,

private static ApplicationContext context = new ClassPathXmlApplicationContext("client.xml");
context.getBean(name);

在上面的程序中,我们会通过一个上下文加载所有的bean,所以不会涉及到双上下文的问题。

场景2:

接下来,我们需要开发一个web应用程序,并且使用Tomcat容器,在web.xml中我们添加了如下的配置:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

添加该配置后,web应用在启动时会加载applicationContext.xml中定义的所有bean,这里也不会涉及到双上下文。

场景3:

我们在web应用程序中引入了Spring MVC框架,并在web.xml中进行了如下的配置,

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

如此一来,tomcat启动的时候会将springweb-servlet.xml中定义的bean进行初始化。

这个场景下依然没有双上下文的介入。

场景4:

这一次我们希望解耦web框架与底层的业务逻辑框架,因此我们又对web.xml进行了如下的修改,

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

如此一来,就会出现双上下文的情形。

因为tomcat启动时,ContextLoaderListener会初始化所有在applicationContext.xml中定义的beans。

而FrameworkServlet会初始化springweb-servlet.xml中定义的beans。

这时就出现了两个应用上下文,那么这两个上下文是什么关系呢?

我们来看看FrameworkServlet是如何初始化servlet所需要的上下文的。

	protected WebApplicationContext initWebApplicationContext() {
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;

		if (this.webApplicationContext != null) {
			// A context instance was injected at construction time -> use it
			wac = this.webApplicationContext;
			if (wac instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
				if (!cwac.isActive()) {
					// The context has not yet been refreshed -> provide services such as
					// setting the parent context, setting the application context id, etc
					if (cwac.getParent() == null) {
						// The context instance was injected without an explicit parent -> set
						// the root application context (if any; may be null) as the parent
						cwac.setParent(rootContext);
					}
					configureAndRefreshWebApplicationContext(cwac);
				}
			}
		}
......
}

我们可以看到,initWebApplicationContext方法中的第一句就是获取根上下文,有兴趣的同学可以继续跟踪下去,你会发现这个根上下文就是通过ContextLoaderListener加载的应用上下文,到这里我们可以知道这两个上下文是父子的关系。

而且,根据Spring的官方文档,我们也可以获悉到如下的信息:

As detailed in Section 3.13, “Additional Capabilities of the ApplicationContext”, ApplicationContext instances in Spring can be scoped. In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to a given servlet instance.

到这里我们已经弄清楚了第一个问题,那么既然所有的child applicationcontext都可以继承root applicationcontext,为什么AOP代理在Controller层不生效呢?

其实原因很简单,因为Spring AOP Proxy是在上下文初始化的时候通过BeanPostProcessor这个扩展点创建的。而aspectj autoproxy的配置是放在Service层的,那么也就是根上下文初始化的时候会创建相应的AOP proxy,当Controller层代码所在的servlet webapplicationcontext初始化时,AOP proxy已经创建完毕了。这时servlet webapplicationcontext并不会感知到根上下文中创建的AOP proxy。到这里为止就出现了文中开始处提到问题。

问题的原因已经找到了,那么我们该如何进行处理呢?还是像以往一样,留给读者自己思考吧。



原文地址:https://www.cnblogs.com/kaiblog/p/5591912.html