使用eclipse创建springboot需要先安装STS,建议使用idea作为开发工具,方便快捷。
- 创建项目
新建项目,选择maven
下一步,选目录,完成
新建完成后目录结构如下:
2.配置项目maven
3.添加pom.xml内容
主要添加了三个节点:</parent>、 </dependencies>、</build>
改后pom.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.gary</groupId>
<artifactId>new-spring-boot</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.创建application类
在java目录下先创建两层目录:com.gary,再创建application类
package com.gary;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NewSpringBootApplication {
public static void main(String[] args){
SpringApplication.run(NewSpringBootApplication.class, args);
}
}
5.创建controller类
创建controller目录,并创建HelloController类:
package com.gary.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello world";
}
}
6.配置文件
在resources目录下创建配置文件:application.properties
默认端口为8080,可通过server.port修改:
7.启动项目
在NewSpringBootApplication类右键选择run或debug启动项目
访问:http://localhost:8082/hello
输出正常:
8.项目打包
首先上面的pom.xml中已添加了打包需要的配置项:build
Cmd定位到工程目录,new-spring-boot,打包:mavn package
或 mvn package -Dmaven.test.skip=true
在new-spring-boot/target下便生成了jar文件:new-spring-boot-1.0-SNAPSHOT.jar
因为springboot默认内嵌了tomcat,因此可以直接运行:
java -jar .\target\new-spring-boot-1.0-SNAPSHOT.jar
启动后在页面中测试访问正常。