【问题标题】:Spring boot JPA CrudRepository throws NullPointerException on saveSpring boot JPA CrudRepository 在保存时抛出 NullPointerException
【发布时间】:2015-09-14 18:56:07
【问题描述】:

当我尝试通过 RESTful Web 服务保存数据和列表时,我收到 NullPointerException 错误

ApiRestService.java

package com.twitterservice.service;
@RestController
public class ApiRestService {

    private static final Logger logger = LoggerFactory.getLogger(ApiRestService.class);

    @Autowired(required = true)
    ApiRepository ApiRepo;
    TwitterRepository TwitRepo;

    @RequestMapping(value = "/rest/twitterapi", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseEntity<ApiDomain> saveApiKeys(@RequestBody ApiDomain request) {
        ApiRepo.save(request);
        return new ResponseEntity<ApiDomain>(request, HttpStatus.OK);

    }

    @RequestMapping(value = "/rest/twitter", method = RequestMethod.GET)
    @SuppressWarnings("empty-statement")
    public Iterable<TwitterDomain> getAll() throws TwitterException {
        ApiDomain apikeys = ApiRepo.findOne(1L);
        ConfigurationBuilder xb = new ConfigurationBuilder();
        xb.setDebugEnabled(true)
                .setOAuthConsumerKey(apikeys.getConsumerKey())
                .setOAuthConsumerSecret(apikeys.getConsumerSecret())
                .setOAuthAccessToken(apikeys.getAccessToken())
                .setOAuthAccessTokenSecret(apikeys.getAccessTokenSecret());

        TwitterFactory tf = new TwitterFactory(xb.build());
        twitter4j.Twitter tw = tf.getInstance();
        List<Status> statuses = tw.getHomeTimeline();
        for (Status a : statuses) {

            TwitRepo.save(new TwitterDomain(a.getUser().getName(), a.getText(), "stable"));

        }

        Iterable<TwitterDomain> lst = TwitRepo.findAll();

        return lst;
    }
}

ApiDomain.java

package com.twitterservice.dao;
@Entity
public class ApiDomain implements Serializable {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String accountName;
    private String consumerKey;
    private String consumerSecret;
    private String accessToken;
    private String accessTokenSecret;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }

    public String getConsumerSecret() {
        return consumerSecret;
    }

    public void setConsumerSecret(String consumerSecret) {
        this.consumerSecret = consumerSecret;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getAccessTokenSecret() {
        return accessTokenSecret;
    }

    public void setAccessTokenSecret(String accessTokenSecret) {
        this.accessTokenSecret = accessTokenSecret;
    }

    public ApiDomain(String accountName, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
        this.accountName = accountName;
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.accessToken = accessToken;
        this.accessTokenSecret = accessTokenSecret;
    }
public ApiDomain() {
    }
  
    
}

推特域名

    package com.twitterservice.dao;
    
    @Entity
    public class TwitterDomain implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
        private String twitteruser;
        private String twittertext;
        private String status;
    
        public String getTwitteruser() {
            return twitteruser;
        }
    
        public void setTwitteruser(String twitteruser) {
            this.twitteruser = twitteruser;
        }
    
        public String getTwittertext() {
            return twittertext;
        }
    
        public void setTwittertext(String twittertext) {
            this.twittertext = twittertext;
        }
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public TwitterDomain(String twitteruser, String twittertext, String status) {
            
            this.twitteruser = twitteruser;
            this.twittertext = twittertext;
            this.status = status;
        }
    
        public TwitterDomain() {
        }
        
    

}

我的仓库

 package com.twitterservice.repository;


import org.springframework.data.repository.CrudRepository;

public interface TwitterRepository extends CrudRepository<TwitterDomain, Long> {

    List<TwitterDomain> findByTwittertext(String twittertext);
}

当我打电话给服务时出错

java.lang.NullPointerException: null
at com.twitterservice.service.ApiRestService.getAll(ApiRestService.java:71)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
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:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
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:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)

处理错误这一行

 TwitRepo.save(new TwitterDomain(a.getUser().getName(), a.getText(), "stable"));

【问题讨论】:

    标签: java spring web-services jpa


    【解决方案1】:

    发生这种情况是因为您只自动连接了 ApiRepository 字段。

    @Autowired适用于下面的第一个字段,而不是类中的所有字段,您需要在要注入的每个字段上添加注释。

    @Autowired(required = true)
    private ApiRepository ApiRepo;
    @Autowired(required = true)
    private TwitterRepository TwitRepo;
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,经过研究我发现:

      • 案例 1: 如果您没有显式创建构造函数并且没有初始化您正在使用的所有依赖项,则会抛出 nullPointerException

      • 案例2:如果你使用依赖并且没有放@Autowired注解会抛出nullPointerException

      • 案例 3: 如果您没有在类级别使用 @AllArugConstructor 注释,它将抛出 nullPointerException

      您需要使用其中之一来避免 nullPointerException 上的 save 方法。

      【讨论】:

        猜你喜欢
        • 2017-07-04
        • 2021-12-16
        • 2019-07-13
        • 2023-03-12
        • 2018-05-12
        • 2018-11-12
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多