service有多个实现类,如何准确注入

总有人问我这个问题,下次甩链接用

  1. 在实现类的@Service注解增加value属性,比如:
public interface IGraphService {
    float getArea();
    float getPerimeter();
}

@Service(value = "circular")
public class CircularImpl implements IGraphService {
    @Override
    public float getArea() {
        return 100;
    }

    @Override
    public float getPerimeter() {
        return 0;
    }
}

// value为默认属性,可以不写
@Service("rectangle")
public class RectangleImpl implements IGraphService {
    @Override
    public float getArea() {
        return 200;
    }

    @Override
    public float getPerimeter() {
        return 0;
    }
}
  1. 使用@Autowired + @Qualifier注解@Resource注解,指定需要注入的service
public class GraphController {
    @Autowired
    @Qualifier("circular")
    IGraphService graphService;

    @GetMapping("getArea")
    public float getArea() {
        return this.graphService.getArea();
    }
}

public class GraphController {
    @Resource(name="circular")
    IGraphService graphService;

    @GetMapping("getArea")
    public float getArea() {
        return this.graphService.getArea();
    }
}
  1. 那么@Autowired@Resource有什么区别呢?
    其实在我看来,除了使用上有细微差别外,在效果上没有啥区别。
    另外就是出处不通@Autowired是Spring的,而@Resource属于J2EE。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容