@Autowired无法在EndpointInterceptor中工作

时间:2019-01-16 07:55:05

标签: java spring-ws

我有一个自定义的EndpointInterceptor实现;

@Component
public class MyEndpointInterceptor implements EndpointInterceptor {

@Autowired
private Jaxb2Marshaller marshaller;

@Override
public boolean handleRequest(MessageContext messageContext, Object o) throws Exception {
    return true;
}

@Override
public boolean handleResponse(MessageContext messageContext, Object o) throws Exception {
    return true;
}

@Override
public boolean handleFault(MessageContext messageContext, Object o) throws Exception {
    return true;
}

@Override
public void afterCompletion(MessageContext messageContext, Object o, Exception e) throws Exception {
    // ... do stuff with marshaller
}
}

拦截器被添加到扩展WsConfigurerAdapter;的config类中。

@Configuration
@EnableWs
public class MyWebServiceConfiguration extends WsConfigurerAdapter {
     @Bean(name = "marshaller")
     public Jaxb2Marshaller createJaxb2Marshaller() {
       Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
       return marshaller;
     }
     @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) 
    {
        // Register interceptor
        interceptors.add(new MyEndpointInterceptor());
    }
}

,但是marshaller对象是null

这时我还有什么想念的吗?

2 个答案:

答案 0 :(得分:2)

您的问题是您不让Spring管理MyEndpointInterceptor。使用Spring时,不应直接使用构造函数。但是让Spring为您构建bean。

您的配置应如下所示:

@Configuration
@EnableWs
public class MyWebServiceConfiguration extends WsConfigurerAdapter {
    @Bean(name = "marshaller")
    public Jaxb2Marshaller createJaxb2Marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        return marshaller;
    }

    @Autowired
    private MyEndpointInterceptor myEndpointInterceptor;

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors)
    {
        // Register interceptor
        interceptors.add(myEndpointInterceptor);
    }
}

答案 1 :(得分:0)

如果使用构造方法注入而不是字段注入,您可能会得到一个非常有用的异常,我只能猜测,但是似乎Spring在Spring Context中没有Marshaller,因此您需要在某个地方提供@Bean方法,例如

@Bean
public Jaxb2Marshaller jaxb2Marshaller () {
 return new Jaxb2Marshaller(foo, bar, ..);
}

您可以在此处阅读为什么要避免使用场注入的原因: https://www.vojtechruzicka.com/field-dependency-injection-considered-harmful/