2011-04-05 208 views
3

我已经定义了以下拦截器:弹簧AOP - 切入点/拦截不叫

@Aspect 
public class OpenSessionInRequestInterceptor { 

    private Log log = LogFactory.getLog(getClass()); 

    @Autowired 
    private SessionFactory sessionFactory; 

    public OpenSessionInRequestInterceptor() { 

    } 

    @Around("@annotation(com.sc2.master.aop.hibernate.OpenSession)") 
    public Object processAround(ProceedingJoinPoint pjp) throws Throwable { 
     log.info("Opening Hibernate Session in method "+pjp.getSignature()); 
     Session session = SessionFactoryUtils.getSession(sessionFactory, true); 
     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); 

     Object ret = pjp.proceed(); 

     session.close(); 
     TransactionSynchronizationManager.unbindResource(sessionFactory); 

     log.info("Closing Hibernate Session in method "+pjp.getSignature()); 

     return ret; 
    } 

} 

当我在一个弹簧测试

@OpenSession 
    public void call() { 
     BusinessCustomer customer = (BusinessCustomer) this.customerDao.loadAll().get(0); 
     System.out.println(customer.getContacts().size()); 
    } 

执行下面的代码段的方面方法被调用。要开始测试我的测试用例类看起来如下:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"file:WebContent/WEB-INF/applicationContext.xml"}) 
@Transactional 

然而,当我有@OpenSession注释的方法和部署我的Tomcat服务器上的应用程序,拦截方法不叫。

应用程序上下文定义如下所示:

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

<bean id="openSessionInRequestInterceptor" class="OpenSessionInRequestInterceptor"></bean> 

我绝对想不通,为什么在tomcat的部署时,AOP不起作用。我希望你有一些想法。

解决方案我找到了解决方案。我将我的aop配置放在applicationContext.xml中,但这不起作用。我将配置放在application-servlet.xml中,现在一切正常。有人知道为什么吗?

回答

2

我承认我没有使其工作使用的标记注释,但我需要注释作为参数,所以这个工作:

@Around("@annotation(foo)") 
public Object invoke(ProceedingJoinPoint invocation, Foo foo) throws Throwable 

但是...注意@Transactional也开始发生了会话一个没有开始,所以也许你不需要那个。

更新:如果您的bean是在子上下文中定义的,那么父上下文的aop配置不会影响它们。父上下文不会看到子上下文,而您的x-servlet.xml是子上下文。

+0

如果我改变我的方法签名到'public Object processAround(ProceedingJoinPoint pjp,OpenSession openSession)throws Throwable',我得到异常:“引发:java.lang.IllegalArgumentException:错误:: 0正式未绑定的切入点” 。 – Erik 2011-04-05 11:47:19

+0

@Erik - 但也改变'@annotation(foo)' - 所以没有FQN那里,只是参数名称。 – Bozho 2011-04-05 11:49:49

+0

好的,现在程序编译,但仍然没有调用该方面。是否有某种记录/调试可以用来查看发生了什么? – Erik 2011-04-05 12:05:22

1

要回答为什么你必须把配置在servlet XML去工作:

我假设你正在使用<context:component-scan ...>标签,这是摆在servlet的XML。这就是为什么你需要将它们都放在servlet XML中,否则它们不会“彼此看”。结果,连接没有正确建立。