Posts

Showing posts with the label @Primary

Spring @Primary Annotation Example

Image
In this section we will learn about @Primary  Annotation. When there are multiple beans of the same data-type  in Spring container ,  all of them are qualified to be autowired to single-valued dependency. That causes ambiguity and leads to throw an exception by framework.  To avoid this issue, we can use the Spring-specific @Primary annotation that automatically gives the higher preference to a particular bean.  This annotation can be used on any class annotated with the @Component , @Service & @Repository annotation or on methods annotated with the @Bean annotation. There should be only one @Primary bean among same type of beans. Using @Primary with @Bean Create  MessageService  interface for message service implementations. public interface MessageService { void printMessaage (); } Create implementations -  SMSService  and  EmailService  classes.    public class SMSService implements MessageService{ ...