Home > Software design >  Spring generates two beans of the same instance "MyRepository"
Spring generates two beans of the same instance "MyRepository"

Time:06-18

i'm fairly 'new' to Spring Boot and need a bit of help with CrudRepositories.

My problem is the following: When I want to start my Spring Boot Application, it starts just fine, creates all the tables in the database, but somehow manages to fail, because Spring creates two beans of the same interface:

Note that my package hierarchy looks a bit different. Spring Boot however is referencing the exact same interface, twice.

The bean 'IMyRepository', defined in com.package.IMyRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration, could not be registered. A bean with that name has already been defined in com.package.IMyRepository defined in @EnableJdbcRepositories declared on JdbcRepositoriesRegistrar.EnableJdbcRepositoriesConfiguration and overriding is disabled.

For clarification: I do not have two interfaces declared wit the same name, I do not have any MyRepositoryImpl classes, and I do not have multiple projects with the same hierarchy. (only one: src/main/.../com.(...).IMyRepository)

My Repository interface looks like this:

package com.package.api.components.account.repository;

import com.package.api.components.account.entity.Account;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface IMyRepository extends CrudRepository<Account, Long> {

    Account findByEmail(String email);

    Account findByEmailAndPassword(String email, String password);
}

And the only single time where, I am taking usage of IMyRepository is in this class:

@Component
@AllArgsConstructor
public class AccountService implements IAccountService, IRegisterService, ILoginService {

    private final IAccountRepository accountRepository;

    private final IPasswordValidationService passwordValidationService;
    private final AAccountMapper accountMapper;

    // Code
}

Here are some answers on StackOverflow & co I've already tried, which none off them worked for me:

Thanks you very much for reading this!

CodePudding user response:

Don't put @Repository (or @Component) on the interface, only on the implementation.

CodePudding user response:

As stated in the comments of @M. Deinum, the problem was, that (in my case) I had two spring-boot-starter-data-... dependencies, both of which wanted to create beans of the same class/interface, with the same Impl name.

I solved the problem, by following their instructions:

  1. I deleted the dependency spring-boot-starter-data-jdbc
  2. I also deleted the library from the project and classpath

Another problem was, that my project wouldn't keep running. I, again, solved this problem by following their instructions:

  1. I added the spring-boot-starter-web dependency
  • Related