总有人问我这个问题,下次甩链接用
- 在实现类的
@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;
}
}
- 使用
@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();
}
}
- 那么
@Autowired
和@Resource
有什么区别呢?
其实在我看来,除了使用上有细微差别外,在效果上没有啥区别。
另外就是出处不通@Autowired
是Spring的,而@Resource
属于J2EE。