注入 DAO 的 @Transactional 的 Spring WS 拦截器不起作用

2024-03-07

我们有一个基于 XML 的传统配置 spring-ws 应用程序,其中包含端点拦截器,这些端点拦截器已注入 DAO 以从数据库获取配置。这些 DAO 注入了 hibernate sessionFactory。

当我们升级到 spring 4.2.0.RELEASE(从 spring 3.2.5.RELEASE)和 spring-ws 2.2.1.RELEASE(从 spring-ws 2.1.4.RELEASE)时,我注意到 DAO 不是代理对象拦截器似乎要去 AnnotationActionEndpointMapping 类而不是 PayloadRootAnnotationMethodEndpointMapping 类。

因此,我创建了一个基于 spring-boot 版本 1.3.0.RELEASE 的示例,该示例概述了我们的遗留应用程序,并且问题在 XML 基本配置和基于注释的配置中都很明显。请注意 注释 @EnableTransactionManagement 存在于示例中,并且存在于遗留应用程序中。

如果您从应用程序上下文中注释掉或从@Congiuration对象中注释掉@EnableWS,则DAO是一个代理对象,拦截器似乎将到达正确的端点(即PayloadRootAnnotationMethodEndpointMapping),并且单元测试工作时没有事务错误。

StackTrace when 或 EnableWS 没有注释掉。

org.springframework.ws.soap.client.SoapFaultClientException: Could not obtain transaction-synchronized Session for current thread
    at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38)
    at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:830)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:624)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
    at hello.ApplicationTests.testSendAndReceive(ApplicationTests.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

导致上述异常的 XML 配置摘录:

    <sws:annotation-driven>
    <sws:interceptors>
           <ref bean="loggingInterceptorAU"/>
    </sws:interceptors>


<bean id="loggingInterceptorAU" class="hello.interceptor.LoggingEndpointInterceptor"/>

导致上述异常的注释配置摘录:

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "countries")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("CountriesPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
        wsdl11Definition.setSchema(countriesSchema);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema countriesSchema() {
        return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
    }

    /**
     * Declaring the loggingInterceptor.
     * @return the new logging interceptor.
     */
    @Bean
    public LoggingEndpointInterceptor loggingInterceptor() {
        LoggingEndpointInterceptor loggingEndpointInterceptor = new LoggingEndpointInterceptor();
        return loggingEndpointInterceptor;
    }

    /**
     * Adds interceptors.
     * @param interceptors
     */
    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
          // if these rows are uncommented
          // and payloadRootAnnotationMethodEndpointMapping method is commented you get
          // Error: SoapFaultClientException: Could not obtain transaction-synchronized Session for current thread
          interceptors.add(loggingInterceptor());
          super.addInterceptors(interceptors);
    }


    /**
     * Spring Boot with Plain Hibernate
     * @see {https://github.com/mdeinum/samples/tree/master/spring-boot-plain-hibernate}
     *
     * Need to also set within application.properties.
     * spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
     * @return
     */
    @Bean(name="sessionFactory")
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }
}

在仔细检查 AnnotationActionEndpointMapping 的构成后,我注意到它实现了 BeanPostProcessor。春季多科http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html建议“...因为 AOP 自动代理是作为 BeanPostProcessor 本身实现的,所以 BeanPostProcessor 和它们直接引用的 bean 都没有资格进行自动代理,因此没有编织到其中的方面。” 因此我知道 @Transactional 不起作用。

public class AnnotationActionEndpointMapping extends AbstractActionMethodEndpointMapping implements BeanPostProcessor

我的问题是: *发生了什么变化导致 spring-ws 拦截器默认映射到 AnnotationActionEndpointMapping 类? * 根据 Spring 文档,建议同时使用和/或 @EnableWs 和方法 addInterceptors。如果在我们的遗留应用程序中注释掉会有什么影响吗?

请注意,我们的拦截器仅使用以下内容针对某些请求调用,并且我们不想使用拦截器列表专门创建 PayloadRootAnnotationMethodEndpointMapping bean 来解决此问题:

<sws:interceptors>
 <sws:payloadRoot localPart="TestRequest" namespaceUri="http://www.test.com/test/request/1.0">
...

与其他人声称的不同,这个错误在 Spring-core 5.1.5 和 Spring-ws 3.0.7 中仍然存在。与这个问题有关:为什么@EnableWs从spring bean中删除aop代理 https://stackoverflow.com/questions/50072312/why-enablews-removed-aop-proxy-from-spring-bean。简而言之,问题来自于该方法

@Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {

在 Spring 依赖注入有时间在事务管理下注册 bean 之前被调用。看来Spring-WS中的bean生命周期初始化逻辑与正常的不同。不知道为什么。

这是我对解决这个问题的看法。幸运的是,Spring-WS 使用可变集合而不是不可变集合。当。。。的时候addInterceptors()方法 被调用时,我们可以保存集合,因此我们可以引用 Spring-WS 使用的同一集合实例。稍后您可以正确初始化拦截器 bean 并将其添加到集合中。

你还必须回避这样一个事实:如果你使用@Autowired在进行注释之前,bean 已准备好。因此你必须通过调用手动创建它ApplicationContext.getBean() method.

@EnableWs
@Configuration
// The magic is to implement both ApplicationContextAware 
// that injects the applicationContext for us 
// and BeanPostProcessor that gives us postProcessBeforeInitialization() 
// where we initialize our interceptor correctly 
// and add it to the collection
public class WebServiceConfig extends WsConfigurerAdapter implements ApplicationContextAware, BeanPostProcessor {

    // This is the interceptor that uses dependencies with @Transactional annotation.
    // It will not work with @Autowired
    private MyInterceptorThatHasTransactionalDependencies myInterceptorThatHasTransactionalDependencies;
    // Fortunately Spring WS uses mutable collections so we can fill 
    // this list later on as long as we just initialize it with  
    private List<EndpointInterceptor> interceptors;
    // This is our application context where all the beans are defined
    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // save application context for later use
        this.context = applicationContext;
    }

    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // This method gets called multiple times so initialize interceptor just once
        if(myInterceptorThatHasTransactionalDependencies == null){
            myInterceptorThatHasTransactionalDependencies = context.getBean(MyInterceptorThatHasTransactionalDependencies.class);
            interceptors.add(myInterceptorThatHasTransactionalDependencies);
        }
        return bean;
    }

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        // Save the list of interceptors so we can modify it later on
        this.interceptors = interceptors; 
        if (myInterceptorThatHasTransactionalDependencies == null) {
            System.out.println("myInterceptorThatHasTransactionalDependencies was null like we expected");
        } else {
            interceptors.add(myInterceptorThatHasTransactionalDependencies);
        }
    }
}

只是想让你知道,我不是 Spring bean 生命周期专家,因此可能有一个更好的位置来放置拦截器初始化postProcessBeforeInitialization()。也就是说,这有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

注入 DAO 的 @Transactional 的 Spring WS 拦截器不起作用 的相关文章

随机推荐