Java – two spring service beans with the same class name (different packages) will throw an error even if they use a qualifier

I have the following

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;

But when I try to run, I get

How do I have 2 services with the same name?

Solution

Remove @ qualifier from the class and use @ qualifier only during auto assembly

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

package package2;

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

From @ 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.
 */
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>