Spring - Inject Bean By Name using @Resource

[Updated: Aug 29, 2016, Created: Aug 7, 2016]

Spring supports Java SE Common Annotations (JSR-250). That means, we can use @Resource instead of using the combination of @Autowire and @Qualifier.




Example

Our OrderServiceClient from previous example can be rewritten as:

package com.logicbig.example.client;

import com.logicbig.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;
import java.util.Arrays;


public class OrderServiceClient {

     @Bean(name = "OrderServiceA")
    private OrderService orderService;

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

Note that @Resource can also be used without specifying any name (the qualifier) parameter. If no name is specified explicitly, the default name is derived from the field name or setter method. One of the situation where this name is used is: in matching and injecting beans if we are using Autowire.BY_NAME




Example Project

Dependencies and Technologies Used :

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Spring Resource Example Select All Download
  • spring-resource-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • client
                • service
                  • impl

See Also