由于JBoss AOP暂时的一些限制,比如不能截取系统类,和Tomcat结合起来使用比较困难,先用AspectJ来实践了一下,确实比较方便,下列代码主要展示如何实践的大概框架,简陋至极。
1.PositionManager
public abstract class PositionManager {
protected static PositionManager self = null;
public abstract void addPosition(Position p);
public static PositionManager getInstance(){
if(self == null)
self = new PositionManagerImpl();
return self;
}
}
2.PositionManagerImpl实际实现PositionManager的业务逻辑
public class PositionManagerImpl extends PositionManager {
protected ArrayList positions = new ArrayList();
/* (non-Javadoc)
* @see com.airinbox.jaidwapfactory.position.PositionManager#addPosition(com.airinbox.jaidwapfactory.position.Position)
*/
public void addPosition(Position p) {
System.out.println("add position");
if(!positions.contains(p))
positions.add(p);
}
}
3.CategoryManager
public abstract class CategoryManager {
protected static CategoryManager self = null;
public abstract void addCategory(Category c);
public static CategoryManager getInstance() {
if(self == null)
self = new CategoryManagerImpl();
return self;
}
}
4.CategoryManagerImpl
public class CategoryManagerImpl extends CategoryManager {
protected ArrayList categories = new ArrayList();
/* (non-Javadoc)
* @see com.airinbox.jaidwapfactory.Category.CategoryManager#addCategory(com.airinbox.jaidwapfactory.Category.Category)
*/
public void addCategory(Category c) {
System.out.println("add category");
if(!categories.contains(c))
categories.add(c);
}
}
5.PositionAspect:最关键的aspect的声明,主要说明了如何截取子类的实例,如何获得方法调用的参数等等,由于方法可能会在Jsp中调用,减少麻烦,pointcut声明的时候一般不用call,而用execution。
public aspect PositionAspect {
after(Position p) :
execution(void PositionManager+.addPosition(Position+))
&& args(p){
CategoryManager cm = CategoryManager.getInstance();
Category c = new CategoryImpl(p.getId(),p.getName());
cm.addCategory(c);
}
}
发布到tomcat的时候,只要把aspectjrt.jar copy到$tomcat_home/common/lib目录下就可以了