Spring Certified Professional 2023 · Free Practice Question Medium
Question 12
Which statements about @Autowired are correct? (select 2)
-
A
By default,
@Autowiredrequiredattribute is set tofalse. -
B
When using
@Autowiredon collections, it autowires the first item. -
C
If more than one bean of the same type is available in the container, the framework will throw a fatal exception.
-
D
@Autowiredannotation on such a constructor is no longer necessary if the target bean defines only one constructor to begin with.
Reveal correct answers
Correct answers: C, D
Explanation
Using @Autowired
@Autowired annotation on such a constructor is no longer necessary if the target bean defines only one constructor to begin with.
https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html
required
Declares whether the annotated dependency is required.
Defaults to true.
5. Autowire Disambiguation
By default, Spring resolves @Autowired entries by type. If more than one bean of the same type is available in the container, the framework will throw a fatal exception.
To resolve this conflict, we need to tell Spring explicitly which bean we want to inject.
https://www.baeldung.com/spring-autowire#disambiguation
Collection
You can also instruct Spring to provide all beans of a particular type from the ApplicationContext by adding the @Autowired annotation to a field or method that expects an array of that type.
- public class MovieRecommender {
- private Set<MovieCatalog> movieCatalogs;
- @Autowired
- public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
- this.movieCatalogs = movieCatalogs;
- }
- // ...
- }
https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
