Return to site

🍃🎓 SPRING CERTIFICATION QUESTION: Can you use @Bean together with @Profile?

February 5, 2023

Answer:

𝑷𝒓𝒐𝒇𝒊𝒍𝒆 is itself meta-annotated with 𝑻𝒂𝒓𝒈𝒆𝒕 annotation which means that

it can be applied to methods, and more specifically factory 𝑩𝒆𝒂𝒏 methods.

Use cases for applying 𝑷𝒓𝒐𝒇𝒊𝒍𝒆 annotation on the method level:

1. Bean will only be registered in case the application runs with the same active profile declared in 𝑷𝒓𝒐𝒇𝒊𝒍𝒆 annotation.

2. In case of overloaded 𝑩𝒆𝒂𝒏 methods chosen 𝑷𝒓𝒐𝒇𝒊𝒍𝒆 must be the same for all overloaded methods.

If the profile is inconsistent among all overloaded methods, only 𝑷𝒓𝒐𝒇𝒊𝒍𝒆 of the first declared method will be considered.

Examples of mentioned terms:

𝑴𝒆𝒕𝒉𝒐𝒅𝑳𝒆𝒗𝒆𝒍𝑷𝒓𝒐𝒇𝒊𝒍𝒆𝑪𝒐𝒏𝒇𝒊𝒈𝒖𝒓𝒂𝒕𝒊𝒐𝒏 - demonstrates simplistic usage of 𝑷𝒓𝒐𝒇𝒊𝒍𝒆 annotation applied at method level.

#spring #certificationquestion #vcp