04|编写第一个spring程序
1、通过spring initializr生成程序
- 网址:https://start.spring.io/
- 概览:点击generate生成程序包
2、将生成的程序导入idea
导入后遇到问题:
- 公司私服没有springBoot相关包,需要配置maven阿里云镜像
配置如下:E:\apache-maven-3.6.3\conf\settings.xml
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
3、编写HelloWorld第一个spring程序
- 代码: ```java 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 HelloSpringApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringApplication.class, args);
}
@RequestMapping("/hello")
public String hello(){
return "hello spring";
}
}
- [x] 启动:
点击RUN:<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/611675/1607414426447-fc31a202-59df-47a9-b049-a2b3f84bceda.png#align=left&display=inline&height=161&margin=%5Bobject%20Object%5D&name=image.png&originHeight=161&originWidth=332&size=49176&status=done&style=none&width=332)<br />
- [x] 验证:
termial里执行:curl http://localhost:8080/hello<br />如图:<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/611675/1607414227524-27d8aca8-abbf-4bb1-8a0e-66e11ed0157c.png#align=left&display=inline&height=145&margin=%5Bobject%20Object%5D&name=image.png&originHeight=145&originWidth=645&size=54482&status=done&style=none&width=645)<br />4、spring-actuator健康检查<br />检查这个程序运行状态,引入后重新Run
- [x] 引入依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 验证:
termial里执行:curl http://localhost:8080/actuator/health
- 结果:健康显示UP,不健康显示DOWN, 没引入就404
5、mvn 打包
[x] 引入依赖:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
[x] 执行 mvn clean package(或者 mvn install)进行打包
- 运行jar包:>java -jar hello-spring-0.0.1-SNAPSHOT.jar
如图:
效果跟 Run一样