Home > OS >  Spring Boot application failed to start, bean could not be found
Spring Boot application failed to start, bean could not be found

Time:06-22

My Spring Boot application will not start because a bean could not be found. I have done a lot of investigation and have had many attempts at trying to solve the issue, but none have worked. Below are what the common issues appear to be (and why they haven't solved it for me). Any help or suggestions would be hugely appreciated.

Potential causes of the issue

  1. Not declaring the main class in the correct location

    My folder structure is shown below. I believe this is structure should avoid any NoSuchBeanDefinitionException problems. It may also be worth mentioning here that this is not my entire project. Just the files I think are relevant to this issue.

    Folder structure

    src/
    ├── main/
    │   └── java/
    |       ├── mygroup.tqbcbackend/
    |       |   └── TqbcBackendApplication.java
    |       ├── mygroup.tqbcbackend.model/
    |       |   └── Team.java
    |       ├── mygroup.tqbcbackend.controller/
    |       |   └── TeamController.java
    |       └── mygroup.tqbcbackend.repository/
    |           └── TeamRepository.java
    └── resources/
        └── application.properties
    
  2. Classes are not declared with annotations such as @Repository

    My code is below, I don't believe this is true

  3. This answer suggested removing @Autowired from above private TeamRepository teamRepository; in TeamController.java

    This did actually cause the application to start, but down the line a java.lang.NullPointerException was returned when calling teamRepository.findAll();

Error

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

2022-06-20 22:54:18.006  INFO 23052 --- [  restartedMain] m.tqbcbackend.TqbcBackendApplication     : Starting TqbcBackendApplication using Java 11.0.15 on OD with PID 23052 (C:\Dev\TheQBCarousel\tqbc-backend\target\classes started by odern in C:\Dev\TheQBCarousel\tqbc-backend)
2022-06-20 22:54:18.007  INFO 23052 --- [  restartedMain] m.tqbcbackend.TqbcBackendApplication     : No active profile set, falling back to default profiles: default
2022-06-20 22:54:18.065  INFO 23052 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-06-20 22:54:18.067  INFO 23052 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-06-20 22:54:19.613  INFO 23052 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-06-20 22:54:19.623  INFO 23052 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-06-20 22:54:19.624  INFO 23052 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]     
2022-06-20 22:54:19.867  INFO 23052 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-06-20 22:54:19.867  INFO 23052 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1800 ms
2022-06-20 22:54:20.117  WARN 23052 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'teamController': Unsatisfied dependency expressed through field 'teamRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'mygroup.tqbcbackend.repository.TeamRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-06-20 22:54:20.122  INFO 23052 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]

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

Description:

Field teamRepository in mygroup.tqbcbackend.controller.TeamController required a bean of type 'mygroup.tqbcbackend.repository.TeamRepository' that could not be found.

The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'mygroup.tqbcbackend.repository.TeamRepository' in your configuration.

TeamController.java

package mygroup.tqbcbackend.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import mygroup.tqbcbackend.model.Team;
import mygroup.tqbcbackend.repository.TeamRepository;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/v1/teams")
public class TeamController {

    @Autowired
    private TeamRepository teamRepository;
    
    // Get all teams
    @GetMapping("/all")
    public List<Team> getAllTeams() {
        return teamRepository.findAll();
    }
    
    // Get all active teams
    @GetMapping("/active")
    public List<Team> getAllActiveTeams() {
        return teamRepository.findByIsActiveTrue();
    } 
}

TeamRepository.java

package mygroup.tqbcbackend.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import mygroup.tqbcbackend.model.Team;

@Repository
public interface TeamRepository extends JpaRepository<Team,String>{
    
    public List<Team> findByIsActiveTrue();

}

TqbcBackendApplication.java

package mygroup.tqbcbackend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TqbcBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(TqbcBackendApplication.class, args);
    }

}

application.properties

####### Data-Source Properties #######
spring.datasource.url=jdbc:mysql://localhost:3306/the_qb_carousel?useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 


###### JPA Properties ######
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# Stops SQL column names being automatically renamed to snake case
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

spring.jpa.hibernate.ddl-auto=update
# 
spring.jpa.properties.hibernate.jdbc.batch_size=16

logging.level.org.hibernate.persister.entity=ERROR


#logging.level.org.hibernate.SQL=DEBUG
#logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
#logging.level.org.hibernate.type=TRACE

###### App Properties ######
tqdm.app.jwtSecret= VerySecretKey
tqdm.app.jwtExpirationMs= 86400000
tqdm.app.frontEndURL=http://localhost:8081

###### Email Properties ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.username = [email protected]
spring.mail.password = password
spring.mail.properties.mail.smtp.starttls.required = true
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.connectiontimeout = 5000
spring.mail.properties.mail.smtp.timeout = 5000
spring.mail.properties.mail.smtp.writetimeout = 5000

CodePudding user response:

Hmm..., this should work? Well you can force Spring to look up specific packages for Repositories. Try @EnableJpaRepositories("mygroup.tqbcbackend.repository") on your main.

Stolen from example 12 of Spring Boot Documetation

  • Related