0
我有以下的代码结构:依赖注入接口
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豆,怎么能程序知道挑选哪个绘制形状。圆形或三角形如何被注入图动态。
你的问题不清楚。有些东西必须决定注入哪种形状。你不能注入一个接口,只能注入具体的实例。显示你真正想要完成的事情,而不是一个抽象的想法。 –