@Autowired is not working with jersey and spring

橙三吉。 提交于 2019-12-02 07:57:52

You can try using the SpringServlet instead of the jersey provided servlet container to achieve Jersey-Spring integration.

<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>

The documentation for this class states :

A servlet or filter for deploying root resource classes with Spring integration. This class extends ServletContainer and initiates the WebApplication with a Spring-based IoCComponentProviderFactory, SpringComponentProviderFactory, such that instances of resource and provider classes declared and managed by Spring can be obtained. Classes of Spring beans declared using XML-based configuration or auto-wire-based confguration will be automatically registered if such classes are root resource classes or provider classes. It is not necessary to provide initialization parameters for declaring classes in the web.xml unless a mixture of Spring-managed and Jersey- managed classes is required. The servlet supports configuration of child applicationContexts, see CONTEXT_CONFIG_LOCATION.

I Have encountered this situation, you need to add some jar file

gradle project:

compile group: 'org.glassfish.jersey.ext', name: 'jersey-spring3', version: '2.22.2'

maven project:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.22.2</version>
</dependency>

another solution is web.xml file:

 <servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>cn.ice</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

You have to wire a interface instead of class. so there are two ways:

  • To let BuyerRepo to implement one interface

  • Useing @Inject or @Resource instead of @Autowired

Looks like your buyerRepo has no public setter. It's also not possible to set it through the constructor. How about write a setter for it and put the @Autowired annotation on the setter instead. Like this:

@Repository
public class BuyerRepo extends AbstractRepository {

        private BuyerRepo buyerRepo;

        @Autowired
        public void setBuyerRepo(BuyerRepo buyerRepo)
        {
          this.buyerRepo = buyerRepo;
        }
        //...Other code is omitted.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!