Spring-manage Aspectwerkz Aspects
June 6, 2005 – 22:23 | aop, java, springJonas Bonér devised a clever way to spring-manage aspects in his blog Spring and AspectWerkz - A Happy Marriage. The only drawback in his approach is that the bean factory managing the aspects must be called a certain name, and be created by the SpringAspectContainer, which limits the usability because in many cases (e.g. in a Spring MVC powered Web application) contexts might have to be instantiated somewhere else. So as the first application of the AppContextCollector I described in Global References To ApplicationContext(s) Unintrusively, SpringBeanAspectContainer provides an alternative, unintrusive way to manage aspects in Spring.
The main implementation class is the SpringBeanAspectContainer. (See here for the source code of AppContextCollector)
-
package com.digizen.commons.aop;
-
-
import java.util.Iterator;
-
-
import org.apache.log4j.Logger;
-
-
import org.codehaus.aspectwerkz.AspectContext;
-
import org.codehaus.aspectwerkz.aspect.AbstractAspectContainer;
-
import org.springframework.context.ApplicationContext;
-
-
import com.digizen.commons.spring.AppContextCollector;
-
-
public class SpringBeanAspectContainer extends AbstractAspectContainer {
-
-
private static final Logger LOG = Logger.getLogger(SpringBeanAspectContainer.class);
-
-
public SpringBeanAspectContainer(AspectContext aspectContext) {
-
super(aspectContext);
-
}
-
-
@Override
-
int pos = aspectName.indexOf(':');
-
if (pos> 0) {
-
-
if (LOG.isDebugEnabled()) {
-
LOG.debug("loading aspect bean [" + beanName + "] from Spring context [" + contextKey + "]");
-
}
-
-
return AppContextCollector.getContext(contextKey).getBean(beanName);
-
} else {
-
-
if (LOG.isDebugEnabled()) {
-
LOG.debug("No context key specified, try every one registered with AppContextCollector with bean name ["
-
+ aspectName + "]");
-
}
-
-
for (Iterator<applicationcontext> iAppContext = AppContextCollector.getContextIterator();
-
iAppContext.hasNext(); ) {
-
ApplicationContext appContext = iAppContext.next();
-
if (bean != null) {
-
if (LOG.isDebugEnabled()) {
-
LOG.debug("Found bean '" + aspectName + "'");
-
}
-
return bean;
-
}
-
}
-
}
-
return null;
-
}
-
}
When being called to create an aspect instance, this class parses the aspect name specified its aop.xml definition into a context key and a bean name (e.g. "mainContext:myDAO" is parsed to a Spring bean named "myDAO" defined in an application context keyed by "mainContext" in AppContextCollector), and then uses those to get a bean from a Spring context previously created anywhere else. If the aspect name has only a bean name (i.e. doesn't have a ':' in the name string), the container searches through all the contexts in AppContextCollector until it finds a bean with that name.
