04|编写第一个spring程序

1、通过spring initializr生成程序

image.png
2、将生成的程序导入idea
导入后遇到问题:

  • 公司私服没有springBoot相关包,需要配置maven阿里云镜像

配置如下:E:\apache-maven-3.6.3\conf\settings.xml

  1. <mirror>
  2. <id>nexus-aliyun</id>
  3. <mirrorOf>*</mirrorOf>
  4. <name>Nexus aliyun</name>
  5. <url>http://maven.aliyun.com/nexus/content/groups/public</url>
  6. </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 {

  1. public static void main(String[] args) {
  2. SpringApplication.run(HelloSpringApplication.class, args);
  3. }
  4. @RequestMapping("/hello")
  5. public String hello(){
  6. return "hello spring";
  7. }

}

  1. - [x] 启动:
  2. 点击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 />
  3. - [x] 验证:
  4. 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
  5. - [x] 引入依赖:
  6. ```xml
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-actuator</artifactId>
  10. </dependency>
  • 验证:

termial里执行:curl http://localhost:8080/actuator/health

  • 结果:健康显示UP,不健康显示DOWN, 没引入就404

image.png

5、mvn 打包

  • [x] 引入依赖:

    1. <build>
    2. <plugins>
    3. <plugin>
    4. <groupId>org.springframework.boot</groupId>
    5. <artifactId>spring-boot-maven-plugin</artifactId>
    6. </plugin>
    7. </plugins>
    8. </build>
  • [x] 执行 mvn clean package(或者 mvn install)进行打包

  • 运行jar包:>java -jar hello-spring-0.0.1-SNAPSHOT.jar

如图:
image.png
效果跟 Run一样