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 /><br />
- [x] 验证:
termial里执行:curl http://localhost:8080/hello<br />如图:<br /><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一样