Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

浅谈BeanNameAutoProxyCreator #20

Open
vonzhou opened this issue Jan 16, 2020 · 0 comments
Open

浅谈BeanNameAutoProxyCreator #20

vonzhou opened this issue Jan 16, 2020 · 0 comments
Labels

Comments

@vonzhou
Copy link
Owner

vonzhou commented Jan 16, 2020

有一个这样的场景,项目中有一个module专门处理同一类事情,比如调用外部的RPC、DB操作等,这个module里面的类命名都遵守统一的规范,比如xxx或者xxx。我们需要在每次RPC前后打印出RPC的耗时以及输入和外部返回的结果,如果在每个类里面都做这个事情显得特别冗余,都知道可以使用AOP,那么针对这种情况,哪种方式更好了, BeanNameAutoProxyCreator,之前没有使用过,所以这里做个梳理。

使用方式

针对这种bean name符合一定特征的bean做拦截的话,就是需要配置特定的BeanNameAutoProxyCreator bean,指定bean name的模式和拦截器的名称。

<bean id="fooLogInterceptor" class="com.vonzhou.interceptor.FooLogInterceptor"/>

<bean id="fooLogProxyCreator"
      class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <list>
            <value>*RPC</value>
        </list>
    </property>
    <property name="interceptorNames">
        <value>fooLogInterceptor</value>
    </property>
</bean>

拦截器的实现:

public class FooLogInterceptor implements MethodInterceptor {

   
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();

        Object result = null;
        try {
            result = invocation.proceed();
            return result;
        } catch (Exception e) {
            throw e;
        } finally {

            try {
                // do log

            } catch (Exception e) {
                // todo
            }
        }
    }
}

原理分析

本质上,BeanNameAutoProxyCreator也是一个BeanPostProcessor,在Spring bean初始化后进行了代理拦截。

image

@vonzhou vonzhou added the Spring label Jan 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant