2
respostas

Erro ao tentar subir a aplicação leilão

Estou recebendo o erro ao tentar executar a aplicação "leilão":

____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::        (v2.3.1.RELEASE)

2024-05-14 13:50:06.999  WARN 7264 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2024-05-14 13:50:07.077  WARN 7264 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'lanceController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'br.com.alura.leilao.service.LanceService' available: expected single matching bean but found 2: lanceService,employeeService
Exception in thread "task-2" java.lang.IllegalStateException: EntityManagerFactory is closed
   at org.hibernate.internal.SessionFactoryImpl.validateNotClosed(SessionFactoryImpl.java:509)
   at org.hibernate.internal.SessionFactoryImpl.getProperties(SessionFactoryImpl.java:503)
   at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.findDataSource(DataSourceInitializedPublisher.java:105)
   at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:97)
   at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50)
   at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200)
   at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
   at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
   at java.base/java.lang.Thread.run(Thread.java:833)
2024-05-14 13:50:08.242  WARN 7264 --- [  restartedMain] o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200]
2024-05-14 13:50:08.262 ERROR 7264 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field service in br.com.alura.leilao.controller.LanceController required a single bean, but 2 were found:
   - lanceService: defined in file [C:\Users\thiago.benites.ext\OneDrive - AGE LTDA\Cursos\QA\1821-bdd-cucumber-java-aula1\target\classes\br\com\alura\leilao\service\LanceService.class]
   - employeeService: defined by method 'employeeService' in class path resource [br/com/alura/leilao/integration/service/LanceServiceTest$EmployeeServiceImplTestContextConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
2 respostas

O erro específico indica que há duas instâncias de beans que correspondem ao tipo necessário para o campo service na classe LanceController. O Spring não consegue determinar qual usar automaticamente, resultando no erro.

  1. Marque um dos beans como @Primary: Se você tem controle sobre a configuração dos beans, pode marcar um deles como primário usando a anotação @Primary. Isso indicará ao Spring qual usar por padrão quando houver ambiguidade.

    Exemplo:

    @Service
    @Primary
    public class LanceService implements SomeServiceInterface {
        // implementation
    }
    
  2. Atualize o consumidor para aceitar múltiplos beans: Se faz sentido para a sua aplicação, você pode atualizar o código consumidor para aceitar múltiplos beans injetados. Nesse caso, você precisará modificar o código para lidar com a lista de beans.

  3. Use @Qualifier para identificar o bean a ser consumido: Se preferir escolher explicitamente qual bean usar em cada contexto, você pode usar a anotação @Qualifier para identificar o bean específico a ser injetado.

    Exemplo:

    @Autowired
    @Qualifier("lanceService")
    private SomeServiceInterface service;
    

abraços!

Obrigado!!