【问题标题】:Controller not executed in my Spring Boot application控制器未在我的 Spring Boot 应用程序中执行
【发布时间】:2019-01-07 01:03:20
【问题描述】:

我尝试使用 kotlin 在 Spring Boot 中创建简单的 Hello World 应用程序,但 IntelliJ IDE 向我显示警告说我的控制器类从未使用过,并且指定的端点也无法正常工作。我不知道该怎么处理它。

我使用 Boot Initializr 创建了应用程序,其结构如下所示:

kotlin/
    com.myapp.school/
        Application.kt
        controller/
            HelloController.kt
resources/
    static/
    templates/
        hello.html

这是 Application.kt 的代码:

package com.myapp.school

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

最后,我有一个简单的控制器,只有一种方法:

package com.myapp.school.controller

import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping

@Controller
class HelloController

@GetMapping("/hello")
fun hello(): String {
    System.out.println("Hello from controller")

    return "hello"
}

转到 localhost:8080/hello 会显示带有 404 状态的 whitelabel 错误页面。我读到 Spring 在启动时将注册的端点打印到控制台中,但我没有找到这样的消息。

谁能告诉我怎么了? 谢谢

【问题讨论】:

  • 使用@RestController 而不是@Controller。您当前的控制器将尝试定位名为 hello 的视图。

标签: spring spring-boot kotlin


【解决方案1】:

我认为你的问题是你有一个没有正文的顶级类 (HelloController) 和一个顶级函数 (hello)。您必须使用花括号来确保 helloHelloController 的成员。

你有这个:

@Controller
class HelloController

@GetMapping("/hello")
fun hello(): String {
    System.out.println("Hello from controller")

    return "hello"
}

需要是这样的,所以hello属于HelloController,不在同一级别:

@Controller
class HelloController {

    @GetMapping("/hello")
    fun hello(): String {
        System.out.println("Hello from controller")

        return "hello"
    }
}

另外,将 System.out.println 更改为 println,使其更像 Kotlin。

【讨论】:

  • 你是对的!非常感谢。现在它可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 2021-05-02
  • 2020-03-22
  • 1970-01-01
  • 2019-08-12
  • 2019-11-18
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多