1.

What is @Primary?

Answer»

The @Primary annotation is used in the spring framework to give a bean a higher preference if there are several beans of the same type.

The @Primary annotation can be used directly or indirectly with @COMPONENT or with @Bean annotated methods for any class.

The following examples show the USE of an annotation @Primary. CONSIDER the Car interface below.

public interface Car { public void run(); }

Create two beans that IMPLEMENT the user interface named FastCar and SlowCar.

public class FastCar implements Car { @Override public void run() { System.out.println("Inside run() method of FastCar"); } } public class SlowCar implements Car { @Override public void run() { System.out.println("Inside run() method of SlowCar"); } }

In java - based configuration class, declare the FastCar and SlowCar beans.

@Configuration public class AppConfig { @Bean @Primary public User getFastCar() { return new FastCar(); } @Bean public User getSlowCar() { return new SlowCar(); } }

Now create the main class and run the application.

public class MainApp { public STATIC void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Car car=context.getBean(Car.class); car.run(); context.close(); } }

Output:

Inside run() method of FastCar

From the above output, it is clear that the getFastCar() (method, which is annotated with @Primary, is first autowired.



Discussion

No Comment Found