Home > Software design >  NoUniqueBeanDefinitionException thrown though there is only one implementation
NoUniqueBeanDefinitionException thrown though there is only one implementation

Time:01-20

I have a MyService class which has repository field supposed to be injected.

public class Service {
    @Autowired
    private Repository repository;
// ...ommited
}

And there is MyRepository interface only implemented by MyRepositoryImpl class with @Mapper annotation of MyBatis.

public interface Repository {
// ...ommited
}

@Mapper
public class RepositoryImpl implements Repository {
// ...ommited
}

When I try to start SpringBootApplication, NoUniqueBeanDefinitionException is thrown.

@SpringBootApplication(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
@MapperScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
(...omitted)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.example.MyService':
Unsatisfied dependency expressed through field 'repository'; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type 'com.example.MyRepository' available: 
expected single matching bean but found 2: com.example.MyRepositoryImpl,com.example.MyRepository
(...omitted)

Why is MyRepository interface registered as one of bean even though it doesn't have @Component annotation nor isn't included any bean configurations?

And I found that everything work fine if I don't use FullyQualifiedAnnotationBeanNameGenerator as nameGenerator.

Any ideas?

CodePudding user response:

Spring is not able to figure out the bean whose class is supposed to be implementing the Repository interface.
Put the annotation @Repository above the RepositoryImpl Class. It will find it.

CodePudding user response:

There can be many other ways to mark an interface as a bean. Some of them are:

  1. @RepositoryDefinition above MyRepository interface
  2. MyRepository extends CrudRepository or JpaRepository
Check if any of these exist.
  •  Tags:  
  • Related