当我正在运行测试用例时,实体管理器被成功注入,但在运行web应用程序时抛出NullPointerException [英] when I am running test cases that time entity manager is injected successfully but while running web app its throwing NullPointerException

查看:120
本文介绍了当我正在运行测试用例时,实体管理器被成功注入,但在运行web应用程序时抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题。我使用ApplicatioContext bean使用PersistenceContext注入实体管理器。但是问题是,当我运行测试用例时,实体管理器被注入成功,但在运行web应用程序时抛出NullPointerException



这是abstractRepository我在哪里注入entityManager

  package com.ajit.retail.repository; 

导入javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

public class AbstractRepository {

@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager entityManager;
}

这是我使用实体管理器的存储库

  package com.ajit.retail.repository; 

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

import javax.persistence.NoResultException;

@Repository
公共类BuyerRepo扩展AbstractRepository {
$ b $公共买方getBuyer(字符串买方名称)throws InvalidIdException {
javax.persistence.Query buyerId = entityManager .createNativeQuery(从买方b选择b.buyer_id,其中b.name =:name)。setParameter(name,buyerName);
整数ID;

尝试{
id =(Integer)buyerId.getSingleResult();

} catch(NoResultException e){
return null;
}

return getBuyer(id);


买方getBuyer(long buyerId)抛出InvalidIdException {
Buyer Buyer = entityManager.find(Buyer.class,buyerId); ** ====> NULL **
if(buyer == null)抛出新的InvalidIdException(无效的文章ID);
退货买家;




$ b $ p
$ b

这是我调用存储库方法的控制器

  package com.ajit.retail.web; 

import com.sun.jersey.spi.inject.Inject;
import com.ajit.retail.exception.InvalidIdException;
import com.ajit.retail.model.Buyer;
import com.ajit.retail.repository。*;
import org.springframework.stereotype.Component;

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

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

@Inject
BuyerRepo buyerRepo;

@GET
@Produces(MediaType.APPLICATION_JSON)
公共采购员searchFields()抛出InvalidIdException {
字符串buyerId =51;
买方买方;

尝试{
买方= buyerRepo.getBuyer(Long.parseLong(buyerId));
} catch(NumberFormatException e){
buyer = buyerRepo.getBuyer(buyerId);
}

return buyer;


这些是传递的单元测试



package com.ajit.retail.repository;

  import com.ajit。 retail.exception.InvalidIdException; 
import org.hamcrest.core.IsEqual;
导入org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.Assert.assertThat;

公共类BuyerRepoTest扩展BaseRepository {
$ b $ @Autowired
私有BuyerRepo buyerRepo;

@Test
public void shouldGiveNameOfGivenBuyerId()throws InvalidIdException {
assertThat(buyerRepo.getBuyer(2).getName(),IsEqual.equalTo(SupervisorDLS));


@Test(expected = InvalidIdException.class)
public void shouldThrowExceptionForInvalidBuyerId()抛出InvalidIdException {
buyerRepo.getBuyer(-10);


这是基础存储库

  package com.ajit.retail.repository; 

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@ContextConfiguration(locations = {classpath:applicationContext.xml})
public class BaseRepository extends AbstractTransactionalJUnit4SpringContextTests {

}

这是applicationContext.xml

 <?xml version =1.0encoding =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/txxmlns: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.ajit.retail/>

< bean id =dataSourceclass =org.springframework.jdbc.datasource.DriverManagerDataSource>
< property name =driverClassNamevalue =org.postgresql.Driver/>
< property name =urlvalue =jdbc:postgresql:// localhost / retail/>
< property name =usernamevalue =retail_user/>
< property name =passwordvalue =password/>
< / bean>

< bean id =entityManagerclass =org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean>
< property name =dataSourceref =dataSource/>

< property name =packagesToScanvalue =com.ajit.retail/>

< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter>
< property name =showSqlvalue =true/>
< property name =databasePlatformvalue =org.hibernate.dialect.PostgreSQLDialect/>
< / bean>
< / property>
< / bean>

< bean id =transactionManagerclass =org.springframework.orm.jpa.JpaTransactionManager>
< property name =entityManagerFactoryref =entityManager/>
< / bean>

< tx:注解驱动的事务管理器=transactionManager/>

< / beans>

请帮助!


 < servlet>替换为


< servlet-name>零售< / 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.ajit.retail.web< / param-value>
< / init-param>

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

<加载启动> 1< /加载启动>
< / servlet>

with

 < servlet的> 
< servlet-name>零售< / 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> com.ajit.retail.web< / param-value>
< / init-param>

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

<加载启动> 1< /加载启动>
< / servlet>


I have a strange problem. I am injecting the entity manager using PersistenceContext using applicatioContext bean. But problem is that when I am running test cases that time entity manager is injected successfully but while running web app its throwing NullPointerException

this is abstractRepository where I am injecting entityManager

package com.ajit.retail.repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

public class AbstractRepository {

    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    EntityManager entityManager;
}

this is my repository where I am using entity manager

package com.ajit.retail.repository;

import com.ajit.retail.exception.InvalidIdException;
import com.ajit.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); **====> NULL**
        if (buyer == null) throw new InvalidIdException("Invalid Article ID");
        return buyer;
    }
}

this is my controller which is calling the repository method

package com.ajit.retail.web;

import com.sun.jersey.spi.inject.Inject;
import com.ajit.retail.exception.InvalidIdException;
import com.ajit.retail.model.Buyer;
import com.ajit.retail.repository.*;
import org.springframework.stereotype.Component;

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

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

    @Inject
    private BuyerRepo buyerRepo;

    @GET
    @Produces(MediaType.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;
    }
}

these are the unit tests which are passing

package com.ajit.retail.repository;

import com.ajit.retail.exception.InvalidIdException;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.Assert.assertThat;

public class BuyerRepoTest extends BaseRepository {

    @Autowired
    private BuyerRepo buyerRepo;

    @Test
    public void shouldGiveNameOfGivenBuyerId() throws InvalidIdException {
        assertThat(buyerRepo.getBuyer(2).getName(), IsEqual.equalTo("SupervisorDLS"));
    }

    @Test(expected = InvalidIdException.class)
    public void shouldThrowExceptionForInvalidBuyerId() throws InvalidIdException {
        buyerRepo.getBuyer(-10);
    }
}

this is the base repository

 package com.ajit.retail.repository;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class BaseRepository extends AbstractTransactionalJUnit4SpringContextTests {

 }

this is the 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.ajit.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="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>

        <property name="packagesToScan" value="com.ajit.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="entityManager"/>
    </bean>

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

    </beans>

Please Help!

解决方案

I solved this problem by replacing

 <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.ajit.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>

with

<servlet>
        <servlet-name>retail</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>com.ajit.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>

这篇关于当我正在运行测试用例时,实体管理器被成功注入,但在运行web应用程序时抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆