有没有更好的方法来使用JavaConfig配置拦截器?

时间:2017-05-22 13:37:12

标签: java spring interceptor spring-java-config

我正在将XML Spring配置移植到JavaConfig。 我的拦截器bean定义如下:

@Autowired
private MyService myServiceImpl;

@Bean
MyService myService() {
    final ProxyFactoryBean proxy = new ProxyFactoryBean();

    final Class<?>[] proxyInterfaces = { MyService.class };
    proxy.setProxyInterfaces(proxyInterfaces);

    proxy.setTarget(this.myServiceImpl);

    final String[] interceptorNames = { "myInterceptor" };
    proxy.setInterceptorNames(interceptorNames);

    return (MyService) proxy.getObject();
}

,其中&#34; myInterceptor&#34; name在编译时未经过验证。

是否有更好的方法使用JavaConfig配置拦截器?

1 个答案:

答案 0 :(得分:0)

配置拦截器的更好方法:

@Configuration
public class MyServiceConfig {
    @Autowired
    private BeanFactory beanFactory;

    @Autowired
    private IMyService myService;

    @Autowired
    private MyInterceptor myInterceptor;

    @Bean
    public IMyService myServiceIntercepted() {
        final Class<?>[] proxyInterfaces = { IMyService.class };
        final Advice[] advices = { this.myInterceptor };
        return createProxy(proxyInterfaces, this.myService, this.beanFactory,
            advices);
    }

    <T> T createProxy(final Class<?>[] proxyInterfaces, final T target,
            final BeanFactory beanFactory) {
        final ProxyFactoryBean proxy =
                createProxyReturnFactoryBean(proxyInterfaces, target, beanFactory);

        return (T) proxy.getObject();
    }

    <T> ProxyFactoryBean createProxyReturnFactoryBean(
            final Class<?>[] proxyInterfaces, final T target, final BeanFactory beanFactory) {
        final ProxyFactoryBean proxy = new ProxyFactoryBean();
        proxy.setBeanFactory(beanFactory);

        if (proxyInterfaces != null) {
            proxy.setProxyInterfaces(proxyInterfaces);
        }

        proxy.setTarget(target);

        return proxy;
    }

    <T> T createProxy(final Class<?>[] proxyInterfaces, final T target,
            final BeanFactory beanFactory, final Advice[] advices) {
        final ProxyFactoryBean proxy =
                createProxyReturnFactoryBean(proxyInterfaces, target, beanFactory);

        for (final Advice advice : advices) {
            proxy.addAdvice(advice);
        }

        return (T) proxy.getObject();
    }
}