Spring autowire interface

后端 未结 2 1352
孤城傲影
孤城傲影 2020-12-06 02:37

I have an Interface IMenuItem

public interface IMenuItem {

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

    String getLink();
    vo         


        
相关标签:
2条回答
  • 2020-12-06 02:52

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

    0 讨论(0)
  • 2020-12-06 03:04

    i believe half of job is done by your @scope annotation , if there is not any-other implementation of ImenuItem interface in your project below will create multiple instances

    @Autowired
    private IMenuItem menuItem
    

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

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

    this will also create multiple instances

    0 讨论(0)
提交回复
热议问题