简体   繁体   English

Spring Boot 应用程序启动失败,找不到 bean

[英]Spring Boot application failed to start, bean could not be found

My Spring Boot application will not start because a bean could not be found.我的 Spring Boot 应用程序将无法启动,因为找不到 bean。 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.我相信这是结构应该避免任何NoSuchBeanDefinitionException问题。 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类没有用 @Repository 等注解声明

    My code is below, I don't believe this is true我的代码在下面,我不相信这是真的

  3. This answer suggested removing @Autowired from above private TeamRepository teamRepository;这个答案建议从上面的private TeamRepository teamRepository; in TeamController.javaTeamController.java

    This did actually cause the application to start, but down the line a java.lang.NullPointerException was returned when calling teamRepository.findAll();这确实导致应用程序启动,但是调用teamRepository.findAll();时返回了java.lang.NullPointerException

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 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 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 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 = mail@gmail.com
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

Hmm..., this should work?嗯......,这应该工作? Well you can force Spring to look up specific packages for Repositories.好吧,您可以强制 Spring 查找存储库的特定包。 Try @EnableJpaRepositories("mygroup.tqbcbackend.repository") on your main.在您的主服务器上尝试@EnableJpaRepositories("mygroup.tqbcbackend.repository")

Stolen from example 12 of Spring Boot DocumetationSpring Boot Documetation的示例 12 中窃取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM