Home > AI > Backend > SpringBoot >

@Primary

Example 1

We have two Employee in the Configuration, @Primary will tell us which one has priority

Config.java

@Configuration
public class Config {

    @Bean
    public Employee JohnEmployee() {
        return new Employee("John");
    }

    @Bean
    @Primary
    public Employee TonyEmployee() {
        return new Employee("Tony");
    }
}

Employee.java

@Data
@AllArgsConstructor
public class Employee {
    public String name;
}

MainApplication.java

@SpringBootApplication
public class MainApplication {

	public static void main(String[] args) {
        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext(Config.class);

        Employee employee = context.getBean(Employee.class);
        System.out.println(employee);

//		SpringApplication.run(MainApplication.class, args);
	}

References:

https://www.baeldung.com/spring-primary

Example 2:

When we have multiple components, we would set which component is more important

Manager.java

public interface Manager {
    String getManagerName();
}

GeneralManager.java

@Component
@Primary
public class GeneralManager implements Manager {
    @Override
    public String getManagerName() {
        return "General manager";
    }
}

DepartmentManager.java

@Component
public class DepartmentManager implements Manager {
    @Override
    public String getManagerName() {
        return "Department manager";
    }
}

Config.java

@Configuration
@ComponentScan(basePackages="com.example.demo10")
public class Config {


}

ManagerService.java

@Service
public class ManagerService {

    @Autowired
    private Manager manager;

    public Manager getManager() {
        return manager;
    }
}

MainApplication.java

@SpringBootApplication
public class MainApplication {

	public static void main(String[] args) {

        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext(Config.class);


        ManagerService service = context.getBean(ManagerService.class);
        Manager manager = service.getManager();

        System.out.println("----------Shark-------");
        System.out.println(manager.getManagerName());

	}

}

Leave a Reply