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.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html


Bad answers:

  1. The @Order annotation 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.

  2. The @Autowired annotation can be used to give precedence to a bean, but only when used in conjunction with the @Qualifier annotation to specify a specific bean to be injected.

  3. The @Component annotation 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.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need