我从服务方法获取NullPointerException

时间:2019-05-21 09:00:11

标签: java spring spring-data-jpa

我正在 Spring MVC 中将 JPA MySQL 数据库一起使用。 在我的 persistence-beans.xml 中,如下所示

    `

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/tx
           https://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/data/jpa
         http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

        <context:component-scan
            base-package="com.nit.SpringMVC_WebApp.repository" />
        <tx:annotation-driven />
        <jpa:repositories
            base-package="com.nit.SpringMVC_WebApp.repository" />

        <bean id="dataSource"
            class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="dirverClassName"
                value="com.mysql.cj.jdbc.Driver" />
            <property name="url"
                value="jdbc:mysql://localhost:3306/nitindb" />
            <property name="username" value="root" />
            <property name="password" value="nitin8855" />
        </bean>

        <bean id="hibernateJpaVendorAdapter"
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />

        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter"
                ref="hibernateJpaVendorAdapter" />
            <property name="packageToScan"
                value="com.nit.SpringMVC_WebApp.entity" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.connection.autocommit">true</prop>
                </props>
            </property>
        </bean>
        <bean id="transactionManager"
            class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
    </beans>

`

和我的service-beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="productService"  class="com.nit.SpringMVC_WebApp.service.ProductServiceImpl">
        <property name="productService"  ref="entityManagerFactory"/>
   </bean>

</beans>

`

applicationContext.xml `

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

   <import resource="service-beans.xml"/>
   <import  resource="persistence-beans.xml"/>

</beans>

`

这是我的服务实现类`

package com.nit.SpringMVC_WebApp.Service;

import java.util.List;

import javax.persistence.EntityManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nit.SpringMVC_WebApp.entity.Product;
import com.nit.SpringMVC_WebApp.repository.ProductRepository;

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {

    private EntityManager entityManager ;

    private ProductRepository producrRepository;

    public void setProducrRepository(ProductRepository producrRepository) {
        this.producrRepository = producrRepository;
    }

    @Override
    public List<Product> getAllProduct() {
        return producrRepository.findAll();
    }

    @Override
    public Product getProductById(int id) {

        return producrRepository.getOne(id);
    }

}

`

和我的控制器`

package com.nit.SpringMVC_WebApp.contoller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nit.SpringMVC_WebApp.Service.ProductServiceImpl;

@Controller
@RequestMapping("/")
public class MainController {

    private ProductServiceImpl productServiceImpl;


    public void setProductServiceImpl(ProductServiceImpl productServiceImpl) {
        this.productServiceImpl = productServiceImpl;
    }


    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String homeController(ModelMap map) {
        String msg = "My name is nitin";
        map.addAttribute("msg", msg);
        System.out.println(productServiceImpl.getAllProduct());
        return "home";
    }

}

`

我认为我无法通过 JPA 连接数据库。它返回空数据。我的凭据绝对正确,因此每当我使用 JdbcTemplate 时,我都会从数据库返回有效数据。 我的控制器也正常工作,每当我调用服务方法时,它都会给我NullPointerException,这意味着数据库未连接并给出了此异常。 堆栈跟踪如下:

SEVERE: Servlet.service() for servlet [dispatcher] threw exception
java.lang.NullPointerException
    at com.nit.SpringMVC_WebApp.contoller.MainController.homeController(MainController.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:530)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:117)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

`

请告诉我如何通过 JPA

连接数据库

2 个答案:

答案 0 :(得分:3)

该错误表明productServiceImplnull。您应该像这样在其上@Autowired

@Autowired
private ProductServiceImpl productServiceImpl;

或者您可以为该类创建一个推荐的构造函数:

@Autowired
public MainController(ProductServiceImpl productServiceImpl){
    this.productServiceImpl = productServiceImpl;
}

您还应该将persistence-beans.xml更改为此:

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

要扫描控制器注释。

答案 1 :(得分:0)

您需要在@AutowiredproductServiceImpl上使用MainController。或通过构造函数注入设置字段。推荐使用后一种方法。