4
votes

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 this I get...

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]

How do I have 2 Services with the same name?

2

2 Answers

5
votes

Remove @Qualifier from class, use @Qualifier while autowiring only

@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.
 */
3
votes

You need to understand the purpose of @Qualifier here.

There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property. In such cases, you can use the @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

What you are trying is to create 2 classes with the same name but in different packages. In order to do that you will need to specify the service's name as a value parameter to the @Service annotation in order to differentiate the two:

package package1;

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

package package2;

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

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