Close

Spring Framework - @Qualifier Examples

Spring Framework 

    @Autowired
@Qualifier("basic-service")
private MyService myService;
Original Post




Using @Qualifier at field injection point.

public class OrderServiceClient {

@Autowired
@Qualifier("OrderServiceA")
private OrderService orderService;

public void showPendingOrderDetails () {
for (String orderId : Arrays.asList("100", "200", "300")) {
System.out.println(orderService.getOrderDetails(orderId));
}
}
}
Original Post




Using Qualifier at bean definition and registration time.

@Configuration
public class AppRunner2 {

@Bean
@Qualifier("OrderServiceA")
public OrderService orderServiceByProvider1() {
return new OrderServiceImpl1();
}

@Bean(name = "OrderServiceB")
public OrderService orderServiceByProvider2() {
return new OrderServiceImpl2();
}

@Bean
public OrderServiceClient createClient() {
return new OrderServiceClient();
}

public static void main(String... strings) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppRunner2.class);
OrderServiceClient bean = context.getBean(OrderServiceClient.class);
bean.showPendingOrderDetails();
}
}
Original Post




Using Autowire.NO mode with @Qualifier.

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

public class AutowireNoExample4 {

public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(Config.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}

public static class Config {

@Bean(autowire = Autowire.NO)
public ClientBean clientBean() {
return new ClientBean();
}

@Bean
public ServiceBean serviceBean1() {
return new ServiceBean("Service Bean 1");
}

@Bean
public ServiceBean serviceBean2() {
return new ServiceBean("Service Bean 2");
}
}

private static class ClientBean {
@Autowired
@Qualifier("serviceBean2")
private ServiceBean serviceBean;

public void doSomething() {
System.out.println(serviceBean.getMsg());
}
}

private static class ServiceBean {
private String msg;

public ServiceBean(String msg) {
this.msg = msg;
}

public String getMsg() {
return msg;
}
}
}
Original Post




See Also