public class User {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
'}';
}
public User(Long id) {
this.id = id;
}
}
@Configuration
public class OtherUserConfiguration {
@Bean
public User user3(){
return new User(3L);
}
@Bean
public User user4(){
return new User(4L);
}
}
@Configuration
public class AutowiredDependencyInjectionDemo {
@Autowired
private Collection<User> allUsers;
@Bean
public User user1(){
return new User(1L);
}
@Bean
public User user2(){
return new User(2L);
}
public static void main(String args[]){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.register(AutowiredDependencyInjectionDemo.class);
ac.register(OtherUserConfiguration.class);
ac.refresh();
AutowiredDependencyInjectionDemo demo = ac.getBean(AutowiredDependencyInjectionDemo.class);
System.out.println(demo.allUsers);
}
}
First, I define four beans called user1, user 2, user 3, user4, where user1 and user2 is defined in AutowiredDependencyInjectionDemo, and user3 and user4 is defined in OtherUserConfiguration.Then, I use @Autowired to annotate the field named allUsers of Collection type, I expect user1 ~ user4 to be injected into allUsers, but things go wrong.
Run the main of AutowiredDependencyInjectionDemo.The program will only print user3 and user4. Why user1 and user2 is not injected into allUsers? Actually, I'm looking forward to output user1, user2, user3 and user4. What's more confusing to me is when I remove this sentence ac.register(OtherUserConfiguration.class);, the program will can print user1 and user2.
I feel this is very confusing for developers.What do you think? Thank you for your reading and looking forward to your reply.
Comment From: sbrannen
Duplicate of #23934
Comment From: chenqimiao
@sbrannen Thank you for your pointing.