Difference between @Qualifier and @Resource

前端 未结 3 630
谎友^
谎友^ 2020-12-07 13:45

I don’t see any difference between two ways, @Qualifier is always used with @Autowired.

@Autowired
@Qualifier(\"alpha\")

3条回答
  •  Happy的楠姐
    2020-12-07 14:35

    I was facing some issues with @Autowired and then started using @Qualifier and I was finally able to find out the when to use @Autowired with @Qualifier when multiple beans of same type are defined.

    Suppose you define 2 beans of same type but different values :

    
         
    
    
         
    
    

    Then if you just are trying to use @Autowire, then you have to use the same variable name as of the bean name else it will give error as multiple types found.

    @Autowired
    AppContext appContext;
    

    For the above use case you have to use Qualifier.

    @Autowired
    @Qualifier("appContext1")
    AppContext appContext;
    

    Instead, if you use the variable name same as bean name, you can eliminate the use of @Qualifier.

    @Autowired
    AppContext appContext1;
    

    I was always using the variable name same as bean name, but accidentally had some other variable name and faced this issue.

    Let me know if there are any doubts.

提交回复
热议问题