As we saw in Inject Spring Bean By Name example that if there are more than one instances available for an injection point then we have to use @Qualifier annotation to resolve ambiguity. As @Qualifier is used at injection point, there might be situations where we don't want to or cannot use @Qualifier . For example, we might not be allowed to modify bean class to but @Qualifier.
The solution is to use @Primary annotation.
@Primary indicates that a particular bean should be given preference when multiple beans are candidates to be autowired to a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
Example
package com.logicbig.example;
public interface Dao {
void saveOrder(String orderId);
}
We are going to create two implementations of above interface to create ambiguity situation.
package com.logicbig.example;
public class DaoA implements Dao {
@Override
public void saveOrder(String orderId) {
System.out.println("DaoA Order saved " + orderId);
}
}
package com.logicbig.example;
public class DaoB implements Dao {
@Override
public void saveOrder(String orderId) {
System.out.println("DaoB Order saved " + orderId);
}
}
Autowiring Dao:
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
public class OrderService {
@Autowired
private Dao dao;
public void placeOrder(String orderId) {
System.out.println("placing order " + orderId);
dao.saveOrder(orderId);
}
}
Defining beans and running the example
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class AppConfig {
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
public Dao daoA() {
return new DaoA();
}
@Bean
@Primary
public Dao daoB() {
return new DaoB();
}
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
OrderService orderService = context.getBean(OrderService.class);
orderService.placeOrder("122");
}
}
Outputplacing order 122 DaoB Order saved 122
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|