user
public class User {
}
userService
@Component
public class UserService {
private User user;
public UserService(User user) {
this.user = user;
System.out.println(user);
System.out.println("一个参数的构造方法");
}
}
config
@ComponentScan("com.luban")
public class config {
@Bean
public User user(){
return new User();
}
}
Main
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(config.class);
UserService userService = applicationContext.getBean("userService", UserService.class);
}
}
输出:
参数里的user是从Bean中拿来的
修改userService
@Component
public class UserService {
private User user;
public UserService(User user) {
this.user = user;
System.out.println(user);
System.out.println("一个参数的构造方法");
}
public UserService(User user,User user1) {
this.user=user;
System.out.println("两个参数的构造方法");
}
}
测试输出:
结论 :
若有多个构造函数,则spring会采用无参构造,若没有无参构造就报错!!!
添加代码
public UserService() {
System.out.println("无参的构造方法");
}
输出
@Autowired的作用
@Component
public class UserService {
private User user;
@Autowired
public UserService(User user) {
this.user = user;
System.out.println(user);
System.out.println("一个参数的构造方法");
}
public UserService(User user,User user1) {
this.user=user;
System.out.println("两个参数的构造方法");
}
}
发现能输出了
两个构造函数都加上@Autowired呢?
仍然会报错!!!
修改
@Component
public class UserService {
private User user;
@Autowired(required = false)
public UserService(User user) {
this.user = user;
System.out.println(user);
System.out.println("一个参数的构造方法");
}
@Autowired(required = false)
public UserService(User user,User user1) {
this.user=user;
System.out.println("两个参数的构造方法");
}
}
结果:选择参数多的构造方法
修改
@ComponentScan("com.luban")
public class config {
@Bean
public User user(){
return new User();
}
@Bean
public User user2(){
return new User();
}
}
输出:
原因是参数多的构造函数中的user1找不到名字为user1的bean
新增person类
public class Person {
}
@ComponentScan("com.luban")
public class config {
@Bean
public User user(){
return new User();
}
@Bean
public User user2(){
return new User();
}
@Bean
public Person person(){
return new Person();
}
}
修改构造函数
@Component
public class UserService {
private User user;
@Autowired(required = false)
public UserService(User user,Person person) {
this.user = user;
System.out.println(user);
System.out.println("person参数的构造方法");
}
@Autowired(required = false)
public UserService(User user,User user1) {
this.user=user;
System.out.println("两个参数的构造方法");
}
}
输出:
参数一样的情况下优先选择上面的