在Tomcat上使用时,BeanUtils.copyProperties()抛出NullPointerException

时间:2018-05-13 05:32:19

标签: java hibernate tomcat nullpointerexception apache-commons-beanutils

BeanUtils.copyProperties()在Tomcat上抛出NullPointerException,但在localhost上运行正常。

我已检查过所有内容,而dto不是null,只有用户的属性为null,这很好。

public void saveUser(UserDTO dto) {
    User user = new User();
    BeanUtils.copyProperties(dto, user);

    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
}

我的User.java

public class User {

    @Id @GeneratedValue
    private long id;

    private String userId;
    private String firstName;
    private String lastName;
    private String email;
    @Enumerated(EnumType.STRING)
    private Role role;
    private String encryptedPassword;
    private String salt;
    private String token;

... getters and setters method ...
}

1 个答案:

答案 0 :(得分:0)

错误是BeanUtils尝试从Role role类中复制User

private Role role;

它会尝试获取Role的属性(通过反射)但是因为rolenull,它会抛出NPE

使用此方法在复制时忽略字段role

public static void copyProperties(Object source,
                              Object target,
                              String... ignoreProperties)