Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire interface

I have an Interface IMenuItem

public interface IMenuItem {

    String getIconClass();
    void setIconClass(String iconClass);

    String getLink();
    void setLink(String link);

    String getText();
    void setText(String text);

}

Then I have a implementation for this interface

@Component
@Scope("prototype")
public class MenuItem implements IMenuItem {

    private String iconClass;
    private String link;
    private String text;

    public MenuItem(String iconClass, String link, String text) {
        this.iconClass = iconClass;
        this.link = link;
        this.text = text;
    }

    //setters and getters

}

Is there any way to create multiple instances of MenuItem from a configuration class, using only the IMenuItem interface? with @autowired or something ? Also is it possible to autowire by specifying the arguments of the constructor ?

like image 774
adi.neag Avatar asked Jun 30 '15 12:06

adi.neag


People also ask

Can we Autowire interface in Spring?

The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.

What happens when you Autowire an interface?

You autowire the interface so you can wire in a different implementation--that's one of the points of coding to the interface, not the class.

How do you Autowire an interface without implementation?

Could we autowire an interface without any implementation in Spring? No. You are trying to create instance for an Interface which is not possible in Java. Save this answer.


1 Answers

@Autowired is actually perfect for this scenario. You can either autowire a specific class (implemention) or use an interface.

Consider this example:

public interface Item {
}

@Component("itemA")
public class ItemImplA implements Item {
}

@Component("itemB")
public class ItemImplB implements Item {
}

Now you can choose which one of these implementations will be used simply by choosing a name for the object according to the @Component annotation value

Like this:

@Autowired
private Item itemA; // ItemA

@Autowired
private Item itemB // ItemB

For creating the same instance multiple times, you can use the @Qualifier annotation to specify which implementation will be used:

@Autowired
@Qualifier("itemA")
private Item item1;

In case you need to instantiate the items with some specific constructor parameters, you will have to specify it an XML configuration file. Nice tutorial about using qulifiers and autowiring can be found HERE.

like image 167
Smajl Avatar answered Oct 18 '22 22:10

Smajl