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豆,怎麼能程序知道挑選哪個繪製形狀。圓形或三角形如何被注入圖動態。
你的問題不清楚。有些東西必須決定注入哪種形狀。你不能注入一個接口,只能注入具體的實例。顯示你真正想要完成的事情,而不是一個抽象的想法。 –