Spring Boot学习笔记——搭建一个最简单的hello world

使用Spring Initializer新建项目

进入https://start.spring.io/新建一个项目,并下载下来。
这就是一个最基础的spring boot项目了。

我这里是基于spring boot 2.0.2版本的。

下载下来的是一个压缩文件,需要先解压。然后在Eclipse中"Import Existing Maven Project"这个项目。

然后执行maven cleanmaven install
这回需要一些时间,因为需要下载一些maven以来的文件。

maven clean成功了,但是maven install报错:

[ERROR] 读取/home/zifeiy/.m2/repository/org/springframework/boot/spring-boot/2.0.2.RELEASE/spring-boot-2.0.2.RELEASE.jar时出错; invalid END header (bad central directory offset)

后来发现是我JAVA_HOME设置错了,应该是/usr/lib/jvm/java-8-oracle,这样就可以了。

新建的项目没有添加spring-boot-starter-web依赖,所以需要在pom.xml中添加该依赖并重新maven install:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>

这里总是提示jar包出错的原因,我总感觉是eclipse里面的maven有问题。

修改DemoApplication.java文件如下:

package com.zifeiy.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {
    
    @RequestMapping("/")
    String hello() {
        return "hello";
    }
    
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

然后登陆http://localhost:8080/就可以发现浏览器中显现出了一个“hello”了。

猜你喜欢

转载自www.cnblogs.com/zifeiy/p/9030969.html
今日推荐