0

当我当时正在运行测试时,@Autowired 正在工作,但是当我运行 Web 应用程序并尝试在那时获取数据时,它会抛出空指针异常。

这是我的控制器

在此 BuyerRepo 始终为空

import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import com.retail.repository.BuyerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/buyer")
@Component
public class BuyerController {

    @Autowired
    private BuyerRepo buyerRepo;

    @GET
    @Produces("application/json")
    public Buyer searchFields() throws InvalidIdException {
        String buyerId = "51";
        Buyer buyer;

        try {
            buyer = buyerRepo.getBuyer(Long.parseLong(buyerId));
        } catch (NumberFormatException e) {
            buyer = buyerRepo.getBuyer(buyerId);
        }

        return buyer;
    }
}

在存储库中,实体管理器始终为空

这是买家存储库

import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;

@Repository
public class BuyerRepo extends AbstractRepository {

    public Buyer getBuyer(String buyerName) throws InvalidIdException {
        javax.persistence.Query buyerId = entityManager.createNativeQuery("select b.buyer_id from buyer b where b.name = :name").setParameter("name", buyerName);
        Integer id;

        try {
            id = (Integer) buyerId.getSingleResult();

        } catch (NoResultException e) {
            return null;
        }

        return getBuyer(id);
    }

    public Buyer getBuyer(long buyerId) throws InvalidIdException {
        Buyer buyer = entityManager.find(Buyer.class, buyerId);
        if (buyer == null) throw new InvalidIdException("Invalid Article ID");
        return buyer;
    }
}

这是 applicationContext.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"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
        http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.retail"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost/retail"/>
        <property name="username" value="retail_user"/>
        <property name="password" value="password"/>
    </bean>

    <bean id="entityManagerOne" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>

        <property name="packagesToScan" value="com.retail"/>

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerOne"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    </beans>

这是 servlet-context.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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">

    <mvc:annotation-driven />
    <context:annotation-config />

    <context:component-scan base-package="com.retail" />

</beans>

这是 web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>retail</servlet-name>

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

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.retail.web</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>

        <servlet-name>retail</servlet-name>

        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
            /WEB-INF/servlet-context.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>/WEB-INF/views/index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
4

4 回答 4

2

您必须连接接口而不是类。所以有两种方法:

  • 让BuyerRepo实现一个接口

  • 使用@Inject 或@Resource 而不是@Autowired

于 2013-05-19T12:33:51.373 回答
2

我遇到过这种情况,需要添加一些jar文件

毕业项目:</p>

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

Maven项目:

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

另一个解决方案是 web.xml 文件:

 <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>
于 2017-01-16T19:44:20.257 回答
1

您可以尝试使用 SpringServlet 而不是 jersey 提供的 servlet 容器来实现 Jersey-Spring 集成。

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

此类的文档说明:

用于使用 Spring 集成部署根资源类的 servlet 或过滤器。该类扩展了 ServletContainer,并使用基于 Spring 的 IoCComponentProviderFactory、SpringComponentProviderFactory 来启动 WebApplication,从而可以获得 Spring 声明和管理的资源和提供者类的实例。如果这些类是根资源类或提供者类,则使用基于 XML 的配置或基于自动连接的配置声明的 Spring bean 类将被自动注册。不需要为在 web.xml 中声明类提供初始化参数,除非需要混合使用 Spring 管理的和 Jersey 管理的类。servlet 支持子 applicationContexts 的配置,请参阅 CONTEXT_CONFIG_LOCATION。

于 2016-03-25T18:29:49.613 回答
0

看起来您的采购商回购没有公共设置器。也不可能通过构造函数来设置它。如何为它编写一个 setter 并将 @Autowired 注释放在 setter 上。像这样:

@Repository
public class BuyerRepo extends AbstractRepository {

        private BuyerRepo buyerRepo;

        @Autowired
        public void setBuyerRepo(BuyerRepo buyerRepo)
        {
          this.buyerRepo = buyerRepo;
        }
        //...Other code is omitted.
}
于 2013-05-19T12:46:12.840 回答