@Autowired not working in EndpointInterceptor

夙愿已清 提交于 2021-02-11 12:04:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!