Java Spring Web应用程序Nullpointer

时间:2017-07-11 18:35:07

标签: java database spring spring-boot spring-data

我目前正在尝试使用Spring启动和Spring数据创建我的第一个Java Web应用程序。 我已经编写了一个Controller,现在尝试在内存数据库中创建Datas。

当我尝试创建一个新用户时,我收到一个nullpointer异常。尽管用户拥有所有价值。

POJO:

package db;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;

private String userName;

private String email;

private String password;

protected User() {}

public Long getId() {
    return id;
}

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

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

DAO:

package db;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

    List<User> findByUserName(String userName);
}

服务:

package db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserService {

    @Autowired
    UserRepository repository;

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public User start() {
        User user = new User();
        user.setEmail("alovela@uk.com");
        user.setUserName("Ada");
        user.setPassword("Password");

        repository.save(user);

        return user;
    }
}

调用UserService.start()时出错;在我的主要:

2017-07-11 20:31:10.027 ERROR 7604 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException:null

2 个答案:

答案 0 :(得分:0)

看起来NPE在线上升了 repository.save(user);

依赖项repository未注入UserService,请使用@Resource@Autowired对其进行注释。

答案 1 :(得分:0)

1.将@Repository添加到UserRepository,以便它可以通过Spring的组件扫描功能获取

 @Repository
    public interface UserRepository extends CrudRepository<User, Long> {

        List<User> findByUserName(String userName);
    }

2.Autowire UserService中的存储库

@Autowired
UserRepository repository;`

P.S。没有必要,但建议在UserService类中将@Repository更改为@Service,因为它更好地反映了此类的用途,并且它也是Spring来映射特定的异常。

@Repository
public class UserService {