无法运行Spring Boot简单REST服务

时间:2018-12-11 09:21:17

标签: spring-boot


我正在尝试运行使用Spring Initializr创建的基本Spring Boot应用程序。我看到该应用程序与Web上提供的许多示例几乎相同,但我找不到“ 404”页面:

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
public class Controller {

        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String hello() {
                return "it works!";

        }
}

这是主要课程:

package com.example.springtest;

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

@SpringBootApplication
public class DemoApplication {

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

pom.xml仅包含网络启动器:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.1.RELEASE</version>
                <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>spring-test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
        <name>demo</name>
        <description>Demo project for Spring Boot</description>

        <properties>
                <java.version>1.8</java.version>
        </properties>

        <dependencies>
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                </dependency>

                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
                </dependency>
        </dependencies>

        <build>
                <plugins>
                        <plugin>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                </plugins>
        </build>


</project>

执行:

$ curl http://localhost:8080

{"timestamp":"2018-12-11T09:18:59.236+0000","status":404,"error":"Not Found","message":"No message available","path":"/"}

我想念任何入门产品吗? 谢谢

1 个答案:

答案 0 :(得分:2)

在主方法类中使用@ComponentScan()批注,并将路径作为参数传递给其余服务组件扫描。

因为默认情况下,它仅包含主类的包和子包中的服务。因此,要添加其他路径服务,您必须在组件扫描注释中传递路径。