`@SpringBootApplication`注解无法在类路径中找到bean。

huangapple go评论70阅读模式
英文:

@SpringBootApplication Annotation not finding beans in classpath

问题

根据我理解,使用@SpringBootApplication等同于同时使用@EnableAutoConfiguration@ComponentScan。因此,我无法理解为什么Spring无法找到我的注解。据我所知,项目结构和注解都是正确的。然而,当我访问映射的端点http://localhost:8080/dashboardhttp://localhost:8080/dashboard/时,出现404错误。

我刚刚使用IntelliJ内置的Spring Initializer创建了一个新的Spring Boot项目,我选择了Spring Web和一些用于Postgres的组件。在项目中,我找不到其他的用于配置的.xml文件。然而,我找到了以下内容:

DataSourceInitializerInvoker.java - 未编辑过

ConfigurationPropertiesAutoConfiguration.java - 未编辑过

我的项目结构如下:

com
+-abcde
  +-appname
    +-controllers
        DashboardController.java
      Application.java

Application.java:

package com.abcde.appname;

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

@SpringBootApplication
public class Application {

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

}

DashboardController.java

package com.abcde.appname.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    public DashboardController() {

    }

    @GetMapping
    public ModelAndView renderDashboard() {
        return new ModelAndView("dashboard/index");
    }

}

除了这些文件之外,我还有以下内容,

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=user
spring.datasource.driver-class-name=org.postgresql.Driver
spring.main.banner-mode=off

build.gradle

plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

group = 'com.abcde'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-freemarker'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.flywaydb:flyway-core'
    runtimeOnly 'org.postgresql:postgresql'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

stacktrace

...

对于这个问题的任何见解将不胜感激。非常感谢。

英文:

From my understanding using @SpringBootApplication is the equivalent of having @EnableAutoConfiguration and @ComponentScan. For this reason I can't understand why Spring isn't finding my annotations. As far as I'm aware the project structure is as it should be and everything is annotated properly. However when I visit the mapped endpoint http://localhost:8080/dashboard or http://localhost:8080/dashboard/, I see a 404 error.

I just created a new Spring Boot project using IntelliJ's built in Spring Initialiser, I selected Spring Web, and a few components for Postgres. Inside the project I can't find any additional .xml files for configuration. However, I did find:

DataSourceInitializerInvoker.java - which hasn't been edited

ConfigurationPropertiesAutoConfiguration.java - which hasn't been edited

Structure of my project is as follows:

com
+-abcde
  +-appname
    +-controllers
        DashboardController.java
      Application.java

Application.java:

package com.abcde.appname;

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

@SpringBootApplication
public class Application {

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

}

DashboardController.java

package com.abcde.appname.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    public DashboardController() {

    }

    @GetMapping
    public ModelAndView renderDashboard() {
        return new ModelAndView("dashboard/index");
    }

}

Alongside these files I also have the following,

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=user
spring.datasource.driver-class-name=org.postgresql.Driver
spring.main.banner-mode=off

build.gradle

plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

group = 'com.abcde'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-freemarker'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.flywaydb:flyway-core'
    runtimeOnly 'org.postgresql:postgresql'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

stacktrace

2020-09-09 23:24:46.053  INFO 57966 --- [           main] c.d.f.Application          : Starting Application on OP-MacBook-Pro.local with PID 57966 (/Users/op/IdeaProjects/lalala/build/classes/java/main started by op in /Users/op/IdeaProjects/lalala)
2020-09-09 23:24:46.054  INFO 57966 --- [           main] c.d.f.Application          : No active profile set, falling back to default profiles: default
2020-09-09 23:24:46.374  INFO 57966 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-09-09 23:24:46.388  INFO 57966 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-09-09 23:24:46.716  INFO 57966 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-09-09 23:24:46.720  INFO 57966 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-09-09 23:24:46.720  INFO 57966 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-09 23:24:46.775  INFO 57966 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-09-09 23:24:46.775  INFO 57966 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 700 ms
2020-09-09 23:24:46.832  INFO 57966 --- [           main] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 6.4.4 by Redgate
2020-09-09 23:24:46.835  INFO 57966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-09-09 23:24:46.872  INFO 57966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-09-09 23:24:46.879  INFO 57966 --- [           main] o.f.c.internal.database.DatabaseFactory  : Database: jdbc:postgresql://localhost:5432/postgres (PostgreSQL 12.3)
2020-09-09 23:24:46.901  INFO 57966 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 1 migration (execution time 00:00.011s)
2020-09-09 23:24:46.905  INFO 57966 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema "public": 10
2020-09-09 23:24:46.905  INFO 57966 --- [           main] o.f.core.internal.command.DbMigrate      : Schema "public" is up to date. No migration necessary.
2020-09-09 23:24:46.960  INFO 57966 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-09 23:24:46.985  INFO 57966 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-09-09 23:24:47.000  WARN 57966 --- [           main] 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
2020-09-09 23:24:47.010  INFO 57966 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.20.Final
2020-09-09 23:24:47.070  INFO 57966 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-09-09 23:24:47.122  INFO 57966 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2020-09-09 23:24:47.253  INFO 57966 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-09 23:24:47.257  INFO 57966 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-09-09 23:24:47.264  INFO 57966 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-09 23:24:47.265  INFO 57966 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-09-09 23:24:47.266  INFO 57966 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-09-09 23:24:47.273  INFO 57966 --- [           main] c.d.f.lalala          : Started Application in 1.401 seconds (JVM running for 1.885)
2020-09-09 23:24:49.520  INFO 57966 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-09-09 23:24:49.520  INFO 57966 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-09-09 23:24:49.524  INFO 57966 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms

Any insight into this problem would be much appreciated. Many thanks

答案1

得分: 0

它可能成功调用了 renderDashboard(),但未找到 "dashboard/index"。您可以通过调试并设置断点或添加日志/System.out println 语句来验证。您的索引文件是否存在并且设置正确?

英文:

It's probably successfully invoking the renderDashboard() and is not finding "dashboard/index". You can verify that by debugging and setting a breakpoint or adding a log/System.out println statement. Does your index file exist and is it setup correctly?

huangapple
  • 本文由 发表于 2020年9月10日 06:20:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63820303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定