运行 Spring Boot 应用程序时出错

Posted

技术标签:

【中文标题】运行 Spring Boot 应用程序时出错【英文标题】:Error Running Spring Boot Application 【发布时间】:2017-02-18 20:36:27 【问题描述】:

我是 Spring Boot 新手。任何时候我运行我的 Spring Boot 应用程序时,都会出错。 在运行我的 Spring Boot 应用程序时需要帮助。

错误信息: 白标错误页面

此应用程序没有显式映射 /error,因此您将其视为后备。

2016 年 10 月 10 日星期一 10:39:54 WAT 出现意外错误(类型=未找到,状态=404)。 没有可用的消息

代码:

    package hello;

    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class GreetingController 

        @RequestMapping("/greeting")
        public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) 
            model.addAttribute("name", name);
            return "greeting";
        

    


package com.HelloWorld;

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

@SpringBootApplication
public class HelloWorldApplication 

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


 - greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + $name + '!'" />
</body>
</html>

【问题讨论】:

您要访问哪个网址? 【参考方案1】:

问题是因为您的控制器与您的 Spring Boot 应用程序类位于不同的包结构中,在这种情况下,需要将 @ComponentScan 添加到 Spring Boot 应用程序类中。

试试这个:

@ComponentScan(basePackages="hello")

【讨论】:

SpringBootApplication 注解等效于使用 Configuration、EnableAutoConfiguration 和 ComponentScan 及其默认属性,它默认扫描所有带有 Component 注解(或“子”注解,如 Controller、Service 等)的 bean。 但是它总是在它的包扫描下查找所有bean,并且无法扫描不同包中的控制器 可以的,你可以试试

以上是关于运行 Spring Boot 应用程序时出错的主要内容,如果未能解决你的问题,请参考以下文章

尝试将 Spring Boot 应用程序与 mongoDB 连接时出错

使用 init.d 运行 Spring Boot Jar 时出错

在 Spring Boot Web 应用程序中创建名称为“entityManagerFactory”的 bean 时出错

在 Spring Boot App 中运行 jar 文件但在本地运行良好时解析 Thymeleaf 模板文件时出错

在centos tomcat上运行Spring Boot应用程序出错

运行 Spring Boot 简单应用程序时找不到 Oracle 驱动程序