【问题标题】:Using MethodInterceptor in Spring在 Spring 中使用 MethodInterceptor
【发布时间】:2014-07-16 15:59:56
【问题描述】:

我有以下配置来拦截方法并在从方法返回后应用通知,但是,以下配置不起作用。你能建议我缺少什么吗?

@Service("txnEventSubscriber")
EventSubscriberImpl
...

@Resource(name="txnEventSubscriber")
    private EventSubscriberImpl subscriber;


    @Bean
    public Advice myAdvice() {
        return new AfterReturningAdvice() {
            @Override
            public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
            {
                System.out.println("inside advice");
            }
        };
    }

    @Bean
    public ProxyFactoryBean myProxyFactoryBean() {
        return new ProxyFactoryBean() {
            private static final long serialVersionUID = 6296720408391985671L;

            @PostConstruct
            public void afterPropertiesSet() throws ClassNotFoundException {
                setTarget(subscriber);
                setInterceptorNames(new String[] {"myAdvice"});
            }
        };
    }

我有 EventSubscriber,当被调用和返回方法时,我需要拦截方法调用并做一些事情......在这种情况下,打印“内部建议”。

我没有看到任何异常,只是没有调用方法建议。

【问题讨论】:

    标签: java spring interceptor spring-aop method-interception


    【解决方案1】:

    首先,我看到您的类名称为EventSubscriberImpl,并且您正在注入相同类型的类。这意味着,您不是在对接口进行编程。在这种情况下,您可能希望 setProxyTargetClass(true); 为您的 ProxyFactoryBean bean 并将 CGLIB 放入项目的类路径中。

    其次,你需要这样的东西

    @Resource(name="myProxyFactoryBean")
    private EventSubscriberImpl subscriber;
    

    只要您想使用您的EventSubscriberImpl 的代理版本。这意味着,您需要通过代理 bean 名称显式获取代理 bean。

    第三,我会使用这样的东西,以避免通过代理名称获取 bean:

    @Resource(name="txnEventSubscriber")
    private EventSubscriberImpl subscriber;
    
    @Bean
    public Advice myAdvice() {
        return new AfterReturningAdvice() {
            public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
            {
                System.out.println("inside advice");
            }
        };
    }
    
    @Bean
    public Advisor myAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(public * com.foo.bar.EventSubscriberImpl.*(..))");
        return new DefaultPointcutAdvisor(pointcut, myAdvice());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多