Spring - @Primary annotation example

Posted on February 7, 2017


Technologies used:   JDK 1.8.0_121 | Spring 4.3.5.RELEASE | Maven 3.3.9 | Eclipse Mars.2 (4.5.2)

In Spring framework, the @Primary annotation is used to give higher preference to a bean, when there are multiple beans of same type.

The @Primary annotation may be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.

The following examples demonstrate the use of the @Primary annotation.

Consider the following User interface.

User.java

package com.boraji.tutorial.spring;

public interface User {
   public void doSomething();
}

Create two beans named as AdminUser and GuestUser, which implement the User interface.

AdminUser.java

package com.boraji.tutorial.spring;

/**
 * @author imssbora
 */
public class AdminUser implements User {

   @Override
   public void doSomething() {
      System.out.println("Inside doSomething() method of AdminUser");
   }

}

GuestUser.java

package com.boraji.tutorial.spring;

/**
 * @author imssbora
 */
public class GuestUser implements User {

   @Override
   public void doSomething() {
      System.out.println("Inside doSomething() method of GuestUser");
   }

}

Declare the AdminUser and GuestUser beans in java based configuration class.

AppConfig.java

package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.boraji.tutorial.spring.AdminUser;
import com.boraji.tutorial.spring.GuestUser;
import com.boraji.tutorial.spring.User;

@Configuration
public class AppConfig {
   @Bean
   @Primary
   public User getAdminUser() {
      return new AdminUser();
   }

   @Bean
   public User getGuestUser() {
      return new GuestUser();
   }
}

 

Now create main class and run application.

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.boraji.tutorial.spring.config.AppConfig;

/**
 * @author imssbora
 */
public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);
      
      User user=context.getBean(User.class);
      user.doSomething();
      
      context.close();
   }
}

Output

Inside doSomething() method of AdminUser

It is clear from the above output that the getAdminUser() method, annotated with @Primary, is autowired first.