Spring Certified Professional 2023 · Free Practice Question Easy
Question 18
Which annotation can be used in Spring to give precedence to a specific bean?
-
A
@Primary -
B
@Order -
C
@Component -
D
@Autowired
Reveal correct answer
Correct answer: A
Explanation
Good answer: The @Primary annotation can be used to indicate that a bean should be given higher precedence over other beans of the same type.
Javadoc:
public @interface Primary
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
Bad answers:
The
@Orderannotation can be used to give priority to a bean, but it only works when multiple beans of the same type are present in the application context.The
@Autowiredannotation can be used to give precedence to a bean, but only when used in conjunction with the@Qualifierannotation to specify a specific bean to be injected.The
@Componentannotation can be used to give precedence to a bean, but only if the bean has a specific name assigned to it and is referred to using that name in other parts of the application.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
