1、问题所在
在使用spring框架中controller依赖user实体类,重载了其默认的构造方法。重载之后 默认的构造方法就会被覆盖。
@Controller
@RequestMapping(value="/user")
public class HelloController{
@Resource
private User user;
@RequestMapping(value="/hello")
public ModelAndView hello() {
System.out.println("Hello,Annotation Spring MVC!");
user.setName("abc");
System.out.print(user.getName());
ModelAndView mv=new ModelAndView();
mv.addObject("msg","ccc");
mv.setViewName("first");
return mv;
}
}
@Component(value = "user")
public class User {
private String name;
private String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
//省略set,get方法
}
2、出现的错误
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
3、分析错误
原因是springioc容器加载bean默认使用无参构造进行初始化。这里我们可以看到提示显示的是没有找到NoSuchBeanDefinition ,就是因为没有定义user的默认构造方法!!!
注意:
spring实例化bean对象,默认是无参构造方法实例化的,这时就需要bean类中存在无参构造方法。