java – 具有相同类名(不同包)的两个Spring Service Beans即使使用限定符也会抛出Error

我有以下……

package package1;

@Service
@Qualifier("kb")
public class UserService {
...
}

package package2;

@Service
@Qualifier("user")
public class UserService {
...
}

@Autowired
@Qualifier("user")
package2.UserService p2;
@Autowired
@Qualifier("kb")
package1.UserService p1;

但当我尝试运行时,我得到……

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [boot.Application]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘userService’ for bean class [package1.UserService] conflicts with existing, non-compatible bean definition of same name and class [package2.UserService]

我如何拥有2个同名服务?

最佳答案
从类中删除@Qualifier,仅在自动装配时使用@Qualifier

@Service("kb")
public class UserService {
...
}

package package2;

@Service("user")
public class UserService {
...
}

来自@Qualifier javadoc

**
 * This annotation may be used on a field or parameter as a qualifier for
 * candidate beans when autowiring. It may also be used to annotate other
 * custom annotations that can then in turn be used as qualifiers.
 */

转载注明原文:java – 具有相同类名(不同包)的两个Spring Service Beans即使使用限定符也会抛出Error - 代码日志