加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java-Spring AOP-未调用切入点/拦截器

发布时间:2020-12-15 01:19:21 所属栏目:大数据 来源:网络整理
导读:我定义了以下拦截器: @Aspectpublic class OpenSessionInRequestInterceptor { private Log log = LogFactory.getLog(getClass()); @Autowired private SessionFactory sessionFactory; public OpenSessionInRequestInterceptor() { } @Around("@annotation

我定义了以下拦截器:

@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>

我绝对无法弄清楚,为什么将AOP部署在tomcat上时不起作用.我希望你有一些想法.

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

最佳答案
我承认我不必使用标记批注来使其工作,但是我需要将该批注作为参数,因此可行:

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

但是..请注意,如果尚未启动@Transactional,它也会启动一个会话,因此也许您并不是真的需要它.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读