Spring bean not injected into CXF web service, Why?

后端 未结 3 439
一整个雨季
一整个雨季 2021-01-02 09:22

I am writing a RESTful service (using CXF on JBoss) in which I have inject another class using Spring (Autowired). But the class is not getting injected and is null.

相关标签:
3条回答
  • 2021-01-02 09:44

    Try to add below method to your web service:

    @PostConstruct
    public void init() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }
    

    The current web application context (usually the one loaded by ContextLoaderListener) will be used for autowiring, so the IMyCore bean has to be defined in the context listener configuration file and not in the web service one.

    0 讨论(0)
  • 2021-01-02 09:48

    If you want to use Spring Beans in CXF Web Service class, then declare WebService as following in the XML configuration file of the CXF (e.g. spring-cxf.xml)

    <bean id="hello" class="demo.spring.service.HelloWorldImpl" />
    <jaxws:endpoint id="helloWorld" implementor="#hello" address="/HelloWorld" />
    

    Declare separated bean for the WebService class and then put it in the endpoint with an ID. Like this you will have spring managed bean, where you can use AutoWired annotations as well.

    Your beans never won't be injected automatically if you will declare your web service as following.

    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
    <jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld"/>
    

    In this case you will need either:

    • Inject spring beans manually

      SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

    • Or retrieve the beans one by one from the spring context

      ApplicationContext context = ...; // your Spring ApplicationContext HelloBean helloBean = (HelloBean) context.getBean("bean");

      I haven't tried this for JAX-RS, but the approach in my opinion should be the same.

      From CXF official documentation.

    0 讨论(0)
  • 2021-01-02 10:02

    Try to add below bean configuration at Beans.xml

    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
    

    In my case, it worked..

    0 讨论(0)
提交回复
热议问题