Spring autowire interface

I have an iMenuItem interface

public interface IMenuItem { String getIconClass(); void setIconClass(String iconClass); String getLink(); void setLink(String link); String getText(); void setText(String text); } 

Then I have an 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 a way to create multiple instances of MenuItem from a configuration class using only the IMenuItem interface? with @autowired or something else? You can also auto-believe by specifying the constructor arguments?

+7
java spring interface autowired
source share
2 answers

@Autowired is actually perfect for this scenario. You can either autwire a specific class (implementation) or use the interface.

Consider the following example:

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

Now you can choose which 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 

To create the same instance several times, you can use the @Qualifier annotation to indicate which implementation will be used:

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

If you need to instantiate elements with specific constructor parameters, you will need to specify its XML configuration file. A good tutorial on using qulifiers and autwiring can be found HERE .

+18
source share

I believe that half of the work is done using the @scope annotation, if your project does not have any other implementation of the ImenuItem interface below, several instances will be created

 @Autowired private IMenuItem menuItem 

but if there are multiple implementations, you need to use the @Qualifer annotation.

 @Autowired @Qualifer("MenuItem") private IMenuItem menuItem 

it will also create multiple instances

+1
source share

All Articles