简体   繁体   中英

Dependency Injection For Interface

I have the following code structure:

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.                
        }
    }

Even if I define the beans in spring.xml, how can the program know which shape to pick for Drawing. How can a Circle or a Triangle be injected into Drawing dynamically .

Even if I define the beans in spring.xml, how can the program know which shape to pick for Drawing. How can a Circle or a Triangle be injected into Drawing dynamically?

No, in your xml (or through annotations) you will provide the implementation class like Triangle so that the container can inject into your Drawing class, like shown below:

<bean id="shape" class="com.myproject.Triangle"/> <!--Triangle is concrete class-->

One more important point you might be interested in is that if there are multiple implementation classes available (for an interface), then you need to tell the Spring container that which implementation needs to be picked & injected. Spring provides various options for this like @Primary or @Qualifier , etc.. by which you tell the container which implementations needs to be used.

You can look here for various bean examples on how they have provided the concrete classes. Also, look here for @Primary usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM