Spring @Primary Annotation
Last Updated :
31 Jul, 2023
@Primary annotation in Spring is used to indicate the primary bean when multiple beans of the same type are present for auto wiring. When multiple beans are eligible for auto wiring the @Primary annotation will help to determine which bean should be given preference.
By applying @Primary annotation to a specific bean we are specifying that it is a primary bean for its respective type. When auto-wiring the dependencies if we are having multiple beans then the bean which is annotated with @Primary annotation will be given high preference compared to other beans.
Examples for @Primary Annotation
Example 1:
Java
@Component
public class Dog {
private String dogBreed;
public Dog(String breed) { this .dogBreed = breed; }
public String getdogBreed() { return dogBreed; }
}
@Component
@Primary
public class GermanShepared extends Dog {
public GermanShepared() { super ( "GermanShepared" ); }
}
@Component
public class LabraDog extends Dog {
public LabraDog() { super ( "LabraDog" ); }
}
|
Explanation:
In the above example, we are creating a class for Dog in which we are creating variables for dog breed names and creating a constructor to initialize it. Also, we are creating a getter method for the same. Then we are creating two classes for the German Shepherd Dog breed and the Labra Dog breed. Both of these classes extend the Dog class. We are annotating both of these classes with @Component annotation which tells Spring to create a bean for each class. To indicate the GermanShepared class as a primary bean we are annotating it with @Primary annotation. This tells Spring that GermanShepared bean should be used when a bean of type Dog is needed.
Example 2:
Java
@Component
public class Movie {
private String movieType;
public Movie(String movieType)
{
this .movieType = movieType;
}
public String getmovieType() { return movieType; }
}
@Component
@Primary
public class Comedy extends Movie {
public Comedy() { super ( "Comedy" ); }
}
@Component
public class Horror extends Movie {
public Horror() { super ( "Horror" ); }
}
|
Explanation:
In the above example we are creating a class for Movie in which we are creating variables for movie type and creating a constructor to initialise it. Also we are creating a getter method for the same. Then we are creating two classes for Comedy movie and Horror movie. Both of this class extends the Movie class. We are annotating both of these classes with @Component annotation which tells spring to create a bean for each class. To indicate Comedy class as a primary bean we are annotating it with @Primary annotation. This tells Spring that Comedy movie bean should be used when a bean of type Movie is needed.
Share your thoughts in the comments
Please Login to comment...