控制器未在我的Spring Boot应用程序中执行

问题描述 投票:0回答:1

我尝试使用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在启动时将注册的端点打印到控制台,但我还没有找到这样的消息。

谁能告诉我有什么问题?谢谢

spring spring-boot kotlin
1个回答
2
投票

我认为你的问题是你有一个没有身体(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。

© www.soinside.com 2019 - 2024. All rights reserved.