In my spring boot application. I created a class name Book and annotated that class with @Component annotation. Then I created a AppConfig class with @Configration annotation and in that class created a method name getBook() annotated with @Bean annotation which returns Book object.
So I was accepting a error as : required a single bean, but 2 were found when I will use @Autowird annotation to inject it but it not gave me any error and created two beans. So I observed that if I use the below code to inject it:
@Autowired
Book book;
It not gives me any error as here instance name is book.
But if I inject it as:
@Autowired
Book obj;
It gives me error as : required a single bean, but 2 were found
Can anyone tell me why it is like that.
- Book class code:
@Component
public class Book {
void readBook() {
System.out.println("reading book");
}
}
- AppConfig class code:
@Configuration
public class AppConfig {
@Bean
Book getBook() {
return new Book();
}
}
- Main class code where I inject it and gets 2 bean found error:
@SpringBootApplication
public class IntroductionToSpringBootApplication implements CommandLineRunner {
@Autowired
Book obj;
public static void main(String[] args) {
SpringApplication.run(IntroductionToSpringBootApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}
- Main class code where I inject it and gets no error:
@SpringBootApplication
public class IntroductionToSpringBootApplication implements CommandLineRunner {
@Autowired
Book book;
public static void main(String[] args) {
SpringApplication.run(IntroductionToSpringBootApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}
Code007 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.