Is it possible to apply Spring AOP to beans that were declared in an application context different from which AOP config is taking place? I have 2 application contexts: dataApplicationContext.xml and webApplicationContext.xml . I would like to declare an aspect in webApplicationContext.xml to intercept method executions of beans that are defined in dataApplicationContext.xml
dataApplicationContext.xml is included in the main applicationContext.xml context file which is booted from main(String args[])
entry point. webApplicationContext.xml is loaded separetly by ContextLoaderListener
which is deployed in an embedded instance of Jetty.
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml"} );
ctx.registerShutdownHook();
Server server = ctx.getBean(Server.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setContextConfigLocation("classpath:webApplicationContext.xml");
ServletHolder servletHolder = new ServletHolder(dispatcherServlet);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addEventListener(new ContextLoaderListener());
context.setInitParameter("contextConfigLocation",
"classpath*:**/webApplicationContext.xml");
context.addServlet(servletHolder, "/*");
context.setSessionHandler(new SessionHandler());
Thanks.
If your spring application loads both context-files it should work out of the box. If not, you have 2 options:
You can definately do that provided your dataApplicationContext.xml
is loaded using the org.springframework.web.context.ContextLoaderListener
and your webApplicationContext.xml
is loaded using the DispatcherServlet
The reason being, by default the Spring container creates two contexts. the root application context
and each Dispatched Servlet has its own web application context
.
The spring documentation clearly mentions this
As detailed in the section entitled Section 3.8, “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 defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
And hence, the bean definitions that you would specify in your root application context
can be accessed by your dispatcher servlet's webapplication context
In your case, provided the first line is true, you can access the AOP declaration from the webApplicationContext.xml
since this is your web context and it can access the root context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.