Discuss / Java / 用了DAO之后User里面constructor的疑惑

用了DAO之后User里面constructor的疑惑

Topic source

请问,在这节的代码里面,user这个class是加了一个不带参数的constructor的

public class User {
private long id;
private String email;
private String password;
private String name;
public User() {
}

如果我去掉这个就会出错Exception in thread "main" org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.example.service.User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.example.service.User.<init>()

一路看下来应该是AbstractDao.getAll这里面BeanPropertyRowMapper.mapRow这里出的错。

我的问题是:

1.想了一下,感觉是应该为了把这个类的字段都提取出来需要实例化它一次(?),而且是对每一条记录?

2.作为一个准则就是应该给每个被Map的类都构建一个无参数的constructor吗?

谢谢

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

默认就有一个无参数构造方法,除非你自己定义了其他构造方法

对的 我是定义了其他的带参数的constructor...

不过感觉如果是需要带参数才能构建的,就不太适合spring这一套来搞?不是说不能就是比较费力.


  • 1

Reply