当前位置: 首页 > 知识库问答 >
问题:

Spring Boot@autowendJpa仓库返回Null

饶志
2023-03-14

我目前正在开发一个基于Spring Boot的应用程序,该应用程序还集成了ActiveMQ功能,以处理两个不同应用程序之间的DB更新。我目前正在尝试集成SpringDataJPA(带hibernate)提供的默认功能来处理与DB相关的操作。当尝试使用JpaRepository将接收日期保存到数据库中时,该日期指示为Null。

类似场景的参考链接

Spring@Autowired无法连接Jpa存储库

其他资源

https://spring.io/guides/gs/accessing-data-jpa/

例外

java.lang.NullPointerException
    at samples.reportdata.reports.sampleSalesReport_Observer.createSampleSalesRecord(sampleSalesReport_Observer.java:107)
    at samples.reportdata.reports.sampleSalesReport_Observer.update(sampleSalesReport_Observer.java:23)
    at samples.reportdata.reports.BaseReport.call(BaseReport.java:36)
    at samples.reportdata.observer.observers.BaseObserver.update(BaseObserver.java:39)
    at samples.reportdata.observer.subject.BaseSubject.notifyAllObservers(BaseSubject.java:36)
    at samples.reportdata.observer.subject.BaseSubject.setMessage(BaseSubject.java:70)
    at samples.reportdata.utilities.CommonConsumer.process(CommonConsumer.java:127)
    at samples.reportdata.Controller.reportController(Controller.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at samples.reportdata.filters.CrossOriginRequestSharingFilter.doFilter(CrossOriginRequestSharingFilter.java:57)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:117)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:110)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)strong text

我的代码段:

应用

  package samples.reportdata;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    import samples.reportdata.utilities.CommonLoader;

      @SpringBootApplication
      /*@Configuration
        @ComponentScan
        @EnableAutoConfiguration
        @EntityScan(basePackages = {"samples.reportdata.pojo"})
        @EnableJpaRepositories(basePackages = {"samples.reportdata.repository"})
        @EnableTransactionManagement*/
        public class RezgReportDataServiceApplication {

            public static void main(String[] args) {
                new CommonLoader();
                SpringApplication.run(RezgReportDataServiceApplication.class, args);
            }

        }

控制器

注意:它充当从活动MQ接收的数据的入口点*

  package samples.reportdata;

    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;

    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    import samples.reportdata.utilities.CommonConsumer;

    @RestController
    public class Controller {

        @RequestMapping(value = "/receive", method = RequestMethod.POST)
        public String reportController(@RequestBody String postPayload, @RequestParam(value = "queue") String queue) {
            String msg = "";
            try {
                System.out.println("queue==>" + queue);
                System.out.println(URLDecoder.decode(postPayload, "UTF-8"));
                msg = CommonConsumer.getInstance().process(URLDecoder.decode(postPayload, "UTF-8"), queue.split("queue://")[1]);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return msg;
        }
    }

实体类示例\销售\报表数据库表的持久类。

package samples.reportdata.pojo;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;

@Entity
@Table(schema="rezbase_v3_reports", name="sample_sales_report")
@NamedQuery(name="sampleSalesReport.findAll", query="SELECT t FROM sampleSalesReport t")
public class sampleSalesReport implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private Integer id;

    @Column(name="booking_channel", length=5)
    private String bookingChannel;

    @Column(name="cancel_charges")
    private double cancelCharges;

    @Column(name="cancel_charges_base")
    private double cancelChargesBase;

    @Column(name="cash_base_fare")
    private double cashBaseFare;

    @Column(name="cash_base_fare_base")
    private double cashBaseFareBase;

    @Column(name="cash_currency", length=10)
    private String cashCurrency;

    @Column(name="cash_land_fare")
    private double cashLandFare;

    @Column(name="cash_land_fare_base")
    private double cashLandFareBase;

    @Column(name="cash_other_tax")
    private double cashOtherTax;

    @Column(name="cash_other_tax_base")
    private double cashOtherTaxBase;

    @Column(name="cash_tot_tax")
    private double cashTotTax;

    @Column(name="cash_tot_tax_base")
    private double cashTotTaxBase;

    @Column(name="cash_yqyrtax")
    private double cashYqyrtax;

    @Column(name="cash_yqyrtax_base")
    private double cashYqyrtaxBase;

    @Column(name="city_id")
    private Integer cityId;

    @Column(name="city_name", length=50)
    private String cityName;

    @Column(length=5)
    private String combination;

    @Column(name="country_id")
    private Integer countryId;

    @Column(name="country_name", length=50)
    private String countryName;

    @Column(name="credit_base_fare")
    private double creditBaseFare;

    @Column(name="credit_base_fare_base")
    private double creditBaseFareBase;

    @Column(name="credit_currency", length=5)
    private String creditCurrency;

    @Column(name="credit_land_fare")
    private double creditLandFare;

    @Column(name="credit_land_fare_base")
    private double creditLandFareBase;

    @Column(name="credit_other_tax")
    private double creditOtherTax;

    @Column(name="credit_other_tax_base")
    private double creditOtherTaxBase;

    @Column(name="credit_tot_tax")
    private double creditTotTax;

    @Column(name="credit_tot_tax_base")
    private double creditTotTaxBase;

    @Column(name="credit_yqyrtax")
    private double creditYqyrtax;

    @Column(name="credit_yqyrtax_base")
    private double creditYqyrtaxBase;

    @Column(name="eticket_number", length=15)
    private String eticketNumber;

    @Column(name="flight_included", length=3)
    private String flightIncluded;

    @Column(length=3)
    private String packagetype;

    @Column(name="passenger_type", length=5)
    private String passengerType;

    @Column(name="payment_category", length=10)
    private String paymentCategory;

    @Column(name="pkg_name", length=40)
    private String pkgName;

    @Column(name="pkg_reservation_number", length=15)
    private String pkgReservationNumber;

    @Column(name="portal_id", length=50)
    private String portalId;

    @Column(name="pos_agent_commision")
    private double posAgentCommision;

    @Column(name="pos_agent_commision_percentage")
    private double posAgentCommisionPercentage;

    @Column(name="pos_gsa_commision")
    private double posGsaCommision;

    @Column(name="pos_gsa_commision_percentage")
    private double posGsaCommisionPercentage;

    @Column(name="pos_total_commision")
    private double posTotalCommision;

    @Column(name="poslocation_currency", length=4)
    private String poslocationCurrency;

    @Column(name="poslocation_currency_id")
    private Integer poslocationCurrencyId;

    @Column(name="poslocation_id")
    private Integer poslocationId;

    @Column(name="poslocation_name", length=50)
    private String poslocationName;

    @Column(name="product_type", length=1)
    private String productType;

    @Column(length=50)
    private String region;

    @Column(name="region_id")
    private Integer regionId;

    private Integer resconfirmid;

    @Temporal(TemporalType.DATE)
    @Column(name="reservation_date")
    private Date reservationDate;

    @Column(name="reservation_no", length=15)
    private String reservationNo;

    private Integer respkgconfirmid;

    @Column(length=2)
    private String resstatus;

    @Column(name="supconf_number", length=20)
    private String supconfNumber;

    @Column(name="total_cancelation_charge")
    private double totalCancelationCharge;

    @Column(name="total_cancelation_charge_base")
    private double totalCancelationChargeBase;

    private double yqyrtax;

    @Column(name="yqyrtax_base")
    private double yqyrtaxBase;

    public sampleSalesReport() {
    }

    /*Note:Getters and setters for above mentioned fields have been omitted for clarity*/

    }

/sampleSalesReportRepository(注意:这个不能自动生成并返回Null)/

package samples.reportdata.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import samples.reportdata.pojo.sampleSalesReport;

@Repository
public interface sampleSalesReportRepository extends JpaRepository<sampleSalesReport, Integer>   {

    List<sampleSalesReport> findAll();

    sampleSalesReport findOne(Integer id);
}

服务

package samples.reportdata.reports;

import java.util.Date;
import java.util.List;

import javax.xml.ws.soap.Addressing;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import samples.reportdata.pojo.sampleSalesReport;
import samples.reportdata.repository.sampleSalesReportRepository;

@ComponentScan
public class sampleSalesReport_Observer extends BaseReport {

    @Override
    public void update() throws Exception {
        System.out.println("sampleSalesReport_Observer " + this.getSubject().getData());
        this.setMessage("message");
        try {
            createSampleSalesRecord();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  /*Note:This is the Object that does not get auto wired*/
    @Autowired
    private sampleSalesReportRepository sampleSalesReportRepository;

    /*Save Sample Record to DB*/
    public List<sampleSalesReport> createSampleSalesRecord() {

       //Note:sample data set to check JPA operation
        sampleSalesReport sampleSalesReport= new sampleSalesReport();
        Date dNow = new Date( );

        sampleSalesReport.setId(6);
        sampleSalesReport.setProductType("F");
        sampleSalesReport.setResconfirmid(123);
        sampleSalesReport.setRegion("Asia");
        sampleSalesReport.setRegionId(21);
        sampleSalesReport.setCountryName("Sri Lanka");
        sampleSalesReport.setCountryId(123);
        sampleSalesReport.setCityId(22);
        sampleSalesReport.setCityName("Colombo");
        sampleSalesReport.setPoslocationName("Pos_colombo");
        sampleSalesReport.setPoslocationId(100);
        sampleSalesReport.setBookingChannel("CC");
        sampleSalesReport.setPoslocationCurrency("LKR");
        sampleSalesReport.setPoslocationCurrencyId(180);
        sampleSalesReport.setReservationDate(dNow);
        sampleSalesReport.setFlightIncluded("F");
        sampleSalesReport.setPkgReservationNumber("P1234567");
        sampleSalesReport.setPackagetype("D");
        sampleSalesReport.setCombination("FHA");
        sampleSalesReport.setReservationNo("F0001W090308");
        sampleSalesReport.setEticketNumber("1571234567890");
        sampleSalesReport.setPkgName("FlightOne");
        sampleSalesReport.setPaymentCategory("Credit");
        sampleSalesReport.setSupconfNumber("PAY-12345678");
        sampleSalesReport.setPassengerType("ADT");
        sampleSalesReport.setPosAgentCommisionPercentage(10.00);
        sampleSalesReport.setPosAgentCommision(20.33);
        sampleSalesReport.setPosAgentCommisionPercentage(12.00);
        sampleSalesReport.setPosAgentCommision(30.66);
        sampleSalesReport.setPosTotalCommision(50.99);
        sampleSalesReport.setResstatus("N");
        sampleSalesReport.setCashCurrency("LKR");
        sampleSalesReport.setCashLandFare(100.00);
        sampleSalesReport.setCashBaseFare(100.00);
        sampleSalesReport.setCashTotTax(220.00);
        sampleSalesReport.setCashYqyrtax(10.00);
        sampleSalesReport.setCashOtherTax(10.00);
        sampleSalesReport.setCashLandFareBase(100.00);
        sampleSalesReport.setCashBaseFareBase(100.00);
        sampleSalesReport.setCashTotTaxBase(220.00);
        sampleSalesReport.setCashYqyrtaxBase(10.00);
        sampleSalesReport.setCashOtherTaxBase(10.00);
        sampleSalesReport.setCreditCurrency("OMR");
        sampleSalesReport.setCreditLandFare(200.00);
        sampleSalesReport.setCreditBaseFare(200.00);
        sampleSalesReport.setCreditTotTax(440.00);
        sampleSalesReport.setCreditYqyrtax(20.00);
        sampleSalesReport.setCreditOtherTax(20.00);
        sampleSalesReport.setCreditLandFareBase(200.00);
        sampleSalesReport.setCreditBaseFareBase(200.00);
        sampleSalesReport.setCreditTotTaxBase(440.00);
        sampleSalesReport.setCreditYqyrtaxBase(20.00);
        sampleSalesReport.setCreditOtherTaxBase(20.00);
        sampleSalesReport.setYqyrtax(40.00);
        sampleSalesReport.setYqyrtaxBase(80.00);
        sampleSalesReport.setCancelCharges(1.00);
        sampleSalesReport.setCancelChargesBase(2.00);
        sampleSalesReport.setTotalCancelationCharge(1.00);
        sampleSalesReport.setTotalCancelationChargeBase(2.00);

      /*Note: This is the line the nullpoint is thrown for sampleSalesReportRepository*/
        sampleSalesReportRepository.save(sampleSalesReport);

        return sampleSalesReportRepository.findAll();
    }
}

共有2个答案

鲜于璞瑜
2023-03-14

您在sampleSalesReport\u Observer上应用了不正确的注释@ComponentScan

将其移除并应用@组件

当spring boot应用程序扫描已注册的组件时,@Component将使其有资格被视为组件,在您的情况下,它就是sampleSalesReport\u Observer,一旦找到它,所有必需的依赖项/bean/其他已注册组件都将被删除自动接线根据您的要求。在您的情况下,它在sampleSalesReportRepository上失败,因为从未将sampleSalesReport\u Observer检测为组件

夏建木
2023-03-14

对于类sampleSalesReport\u Observer,您应该使用@Component而不是@ComponentScan

 类似资料:
  • 我想在下面返回JSON。 {“名字”:“杰基”} 新来的春靴在这里。1天大。有没有合适的方法可以做到这一点?

  • 我正在使用Spring boot来渲染页面。我也使用了叶子。但是我在从浏览器调用它时得到了下面提供的异常。 我已经编写了视图解析器类,当我使用为此。 和我在应用程序中提到的一样。yml也是。应用yml是 这是我的Controller类,负责渲染index.jspMainController.class

  • Repository,仓库,简称 Repo。为项目添加一个 Git 仓库以后,你就可以用 Git 为项目做版本控制了。 git init 上面的命令可以为项目初始化一个仓库,这个动作只需要执行一次,它会在项目下面创建一个 .git 目录,Git 会把它需要的东西存储在这个 .git 目录里面,它其实就是项目的仓库。 练习 1,创建一个项目。打开你的命令行界面,执行: cd ~/desktop m

  • 仓库(Repository),这里指的是可以使用包管理工具安装的软件包的列表。系统自带一些仓库,如果你发现要安装的包在这些仓库里不存在,你可能需要在系统上安装额外的仓库。 仓库列表 先查看一下安装在系统上的仓库列表,执行: yum repolist 返回类似的东西: repo id repo name

  • 镜像构建完成后,可以很容易的在当前宿主机上运行,但是,如果需要在其它服务器上使用这个镜像,我们就需要一个集中的存储、分发镜像的服务,Docker Registry 就是这样的服务。 一个 Docker Registry 中可以包含多个 仓库(Repository);每个仓库可以包含多个 标签(Tag);每个标签对应一个镜像。 通常,一个仓库会包含同一个软件不同版本的镜像,而标签就常用于对应该软件的

  • 本文向大家介绍详解Maven仓库之本地仓库、远程仓库,包括了详解Maven仓库之本地仓库、远程仓库的使用技巧和注意事项,需要的朋友参考一下 什么是Maven仓库 在不用Maven的时候,比如说以前我们用Ant构建项目,在项目目录下,往往会看到一个名为/lib的子目录,那里存放着各类第三方依赖jar文件,如log4j.jar,junit.jar等等。 每建立一个项目,你都需要建立这样的一个/lib目