Настройка Rest (Джерси) с помощью Spring

Я пытаюсь использовать Джерси 1.8 с Spring 4. Но я не могу внедрить зависимость в Rest Class с помощью Spring.

Каждый раз, когда я пытаюсь вызвать автозависимость, я получаю NULL. Может ли кто-нибудь предположить, почему моя зависимость не внедряется?

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
        http://java.sun.com/xml/ns/javaee/web-app
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <context:component-scan base-package="org.portal.services"></context:component-scan>
    <context:annotation-config />

    <bean
        class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location">
            <value>WEB-INF/dataSource.properties</value>
        </property>
    </bean>
    <import resource="hibernate.cfg.xml" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="addCountryService" class="org.portal.services.AddCountryService">
        <property name="addCountryProcessor" ref="addCountryProcessor"></property>
    </bean>

    <bean id="addCountryProcessor" class="org.portal.processors.AddCountryProcessor">
        <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>


</beans>
5.xsd"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet> <servlet-name>Rest</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>org.portal.services</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Rest</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>

весна-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <context:component-scan base-package="org.portal.services"></context:component-scan>
    <context:annotation-config />

    <bean
        class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location">
            <value>WEB-INF/dataSource.properties</value>
        </property>
    </bean>
    <import resource="hibernate.cfg.xml" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="addCountryService" class="org.portal.services.AddCountryService">
        <property name="addCountryProcessor" ref="addCountryProcessor"></property>
    </bean>

    <bean id="addCountryProcessor" class="org.portal.processors.AddCountryProcessor">
        <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>


</beans>

Отдых Колтроллер

package org.portal.services;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.portal.dto.Country;
import org.portal.processors.AddCountryProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

@Component
@Path("/Country")
public class AddCountryService {

    @Autowired
    private AddCountryProcessor addCountryProcessor;

    @POST
    @Path("/addCountry")
    @Produces(MediaType.APPLICATION_XML)
    @Consumes(MediaType.APPLICATION_XML)
    public String addCountry(String newCountry) {

        XStream xStream = new XStream(new DomDriver());
        xStream.alias("country", Country.class);
        xStream.alias("id", String.class);
        xStream.alias("name", String.class);
        xStream.alias("region", Integer.class);

        Country country  = (Country)xStream.fromXML(newCountry);
        System.out.println("processor is "+addCountryProcessor);

        if(country != null){
            addCountryProcessor.addCountry(country);
        }
        return newCountry;
    }

    public void setAddCountryProcessor(AddCountryProcessor addCountryProcessor) {
        this.addCountryProcessor = addCountryProcessor;
    }

    public AddCountryProcessor getAddCountryProcessor() {
        return addCountryProcessor;
    }

}

После отправки запроса на «http://localhost:7070/HumanResourcePortal/rest/Country/addCountry», поток подходит к методу «addCountry()», но затем печатает addCountryProcessor как null


person shivam    schedule 10.10.2017    source источник
comment
Можете ли вы проверить журналы во время начала войны или при развертывании, если вы получаете ошибку при создании экземпляра класса AddCountryProcessor или в спящем режиме?   -  person Amit K Bist    schedule 11.10.2017
comment
Нет ошибки в консоли для создания экземпляра класса AddCountryProcessor   -  person shivam    schedule 11.10.2017
comment
Возможный дубликат этого вопроса, и вы сможете решить его с помощью этот ответ. Надеюсь это поможет. Если вы не хотите менять сервлет, попробуйте использовать @com.sun.jersey.spi.inject.Inject вместо Autowired.   -  person Rishikesh Darandale    schedule 11.10.2017
comment
Спасибо, Ришикеш, @com.sun.jersey.spi.inject.Inject решил проблему.   -  person shivam    schedule 11.10.2017
comment
не могли бы вы объяснить мне разницу между классом сервлета com.sun.jersey.spi.container.servlet.ServletContainer и com.sun.jersey.spi.spring.container.servlet.SpringServlet   -  person shivam    schedule 11.10.2017
comment
Как вы можете видеть из моего web.xml, я использую класс сервлета для отдыха — com.sun.jersey.spi.container.servlet.ServletContainer, когда я изменил его на com.sun.jersey.spi.spring.container.servlet. СпрингСервлет. Я получал java.lang.IllegalStateException: WebApplicationContext не найден: не зарегистрирован ContextLoaderListener?   -  person shivam    schedule 11.10.2017
comment
Зачем возиться со старой версией Джерси в фреймворке, который все равно ее не поддерживает?   -  person K.Nicholas    schedule 11.10.2017


Ответы (1)


Здесь доступны два варианта:

  • Замените @Autowired на @com.sun.jersey.spi.inject.Inject. Эта аннотация @Inject будет внедряться из настроенной среды внедрения зависимостей.

  • Используйте com.sun.jersey.spi.spring.container.servlet.SpringServlet для развертывания ваших ресурсов с интеграцией Spring. Для интеграции Spring вам необходимо включить следующую зависимость:

    <dependency>
      <groupId>com.sun.jersey.contribs</groupId>
      <artifactId>jersey-spring</artifactId>
      <version>1.8</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    

Здесь исключены зависимости Spring, чтобы использовать объявленную вами, а не ту, которая используется jersey-spring.

person Rishikesh Darandale    schedule 11.10.2017
comment
нужна еще одна помощь ................ заполнитель не работает ... из журналов я вижу, что файл свойств загружается, но заполнитель не работает в моем файле гибернации - person shivam; 14.10.2017
comment
Можете ли вы опубликовать более подробную информацию в другом вопросе? - person Rishikesh Darandale; 16.10.2017