问题
I have a custom EndpointInterceptor
implementation;
@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
}
}
The interceptor is added in the config class that extends WsConfigurerAdapter
;
@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());
}
}
but the marshaller
object is null
.
Is there anything I am missing at this point?
回答1:
Your problem is that you do not let spring manage the MyEndpointInterceptor. When using Spring, you should not use the constructor directly. But let Spring build the bean for you.
You config should look like this:
@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);
}
}
回答2:
If you use Constructor Injection instead of Field Injection you would probably get a quite helpful exception, I can only guess but it seems like Spring has no Marshaller in the Spring Context, you therefore need to provide a @Bean method somewhere,e.g.
@Bean
public Jaxb2Marshaller jaxb2Marshaller () {
return new Jaxb2Marshaller(foo, bar, ..);
}
You can read here why you should try to avoid Field Injection: https://www.vojtechruzicka.com/field-dependency-injection-considered-harmful/
来源:https://stackoverflow.com/questions/54212507/autowired-not-working-in-endpointinterceptor