[英]Dependency Injection For Interface
我有以下代码结构:
interface Shape {
public void draw();
}
class Triangle implements Shape {
public void draw() {
//Draw Triangle
}
}
class Circle implements Shape {
public void draw() {
//Draw Circle
}
}
class Drawing { private Shape shape;
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape=shape;
}
}
class App {
public static void main(String args[]) {
ApplicationContext context = new ClassPathXMLApplicationContext("spring.xml");
Drawing drawing = context.get("drawing");
drawing.draw(); // I want to automatically inject Triangle as default shape inside this drawing object.
}
}
即使我在spring.xml中定义了bean,程序也如何知道为Drawing选择哪种形状。 如何将圆形或三角形动态地注入到工程图中。
即使我在spring.xml中定义了bean,程序也如何知道为Drawing选择哪种形状。 如何将圆形或三角形动态地注入到工程图中?
不,在xml
(或通过注释),您将提供实现类,例如Triangle
以便容器可以注入到您的Drawing
类中,如下所示:
<bean id="shape" class="com.myproject.Triangle"/> <!--Triangle is concrete class-->
您可能感兴趣的另一个重要点是,如果有多个可用的实现类(用于一个接口),那么您需要告诉Spring容器需要选择并注入哪个实现。 Spring为此提供了各种选项,例如@Primary
或@Qualifier
等。通过这些选项,您可以告诉容器需要使用哪些实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.