论坛首页 Java版 Spring

关于用@AspectJ风格定义Pointcut的时候无法拦截接口的问题

浏览 235 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
最后更新时间:2008-07-09
请看我的服务接口:

@Entity
public interface CustomerService {
	/**
	 * 
	 * (此处写功能描述,换行用<b/>,换段用<p/>)
	 * 
	 * @param customer
	 * @return
	 * @see (此处写相关联的一些类名,如果没有,请去掉此注释,如果多于一个,请换行新增一个@see)
	 * @author 你的姓名 新增日期:2008-7-9
	 * @author 你的姓名 修改日期:2008-7-9
	 * @since 1.0
	 */
	@Transactional
	public Long registCustomer(Customer customer);
	
	public void updateCustomer(Customer customer);
	
	public void removeCustomer(Long customerId);
}


我在接口处使用了一个Annotation “@Entity”,在方法registCustomer处也使用了一个Annotation “@Transactional”,

再看我定义的Pointcut和相应的处理Advice:

@Aspect
public class SystemPointcuts {
         @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional) && execution(public * *(..))")    
	public void everyAnnotatedMethod() {}
	
	@Pointcut("@target(javax.persistence.Entity)")    
	public void everyAnnotatedTarget() {}

	@Before("everyAnnotatedTarget()")
	public void afterAddSomething() {   
		System.out.println("Executing add method.");
	}
}


当执行CustomerService的业务方法时候,由于CustomerService存在“@Entity”,符合@Pointcut("@target(javax.persistence.Entity)")的条件,正常情况下,afterAddSomething() 应该被执行,但实际上该方法并没有被AOP唤起,我修改了代码,把“@Entity”放置到CustomerService的实现类CustomerServiceImpl中,这次afterAddSomething() 被正常唤起了。

我想知道的是,SpringAOP的基于自动代理的的拦截机制,Pointcut对应的不是接口吗?请问这个问题如何解决。
   
最后更新时间:2008-07-09
Pointcut("@annotation(org.springframework.transaction.annotation.Transactional) && execution(public * *(..))") 
应该是它的实现类,不是接口
   
0 请登录后投票
最后更新时间:2008-07-09
初步找到问题的原因:annotation不能通过接口继承下来,暂时没有找到比较好的解决方法。

但想了一下,如果要定义为了某“Aspect”服务的Annotation,把它放置于实现类比放置于接口合理,因为接口是不关注实现的,接口只关注其自身需要向外界提供的功能,而“Aspect”是实现的问题,可能某个接口在某种实现场景需要被AOP拦截,但在另一种场景又不需要,比如日志功能,因此,把与“Aspect”有关的东西与接口绑定在一起,实际上该接口已经被假设在某种实现环境了,接口被污染了,所以Aspect的定义应该被延迟到实现类中,有具体实现决定是否需要被某个Aspect处理。这是我的个人理解。
   
0 请登录后投票
最后更新时间:2008-07-09
annotation不会随接口的实现而继承,也不会通过子类的扩展而继承。如果解释annotation的程序是自定义的就比较好处理,可以获得该类的父类和接口从而进一步获得其中的属性和方法上的annotation。
   
0 请登录后投票
论坛首页 Java版 Spring

跳转论坛:
JavaEye推荐