搭建环境
有3种方式搭建环境, 切记,搭建环境必须在有网络的环境下进行,网络不好,可能依赖需要下载个几分钟
方式一: 手动创建
- 创建maven工程或者Module,不需要骨架
- 添加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>
<groupId>com.zuoyueer</groupId>
<artifactId>SpringBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<!--添加起步依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<!--添加web依赖-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
依赖添加成功之后是这样的
3. 创建启动类,
package com.zuoyueer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Zuoyueer
* Date: 2019/12/16
* Time: 21:09
* @projectName Framework
* @description: springBoot应用的入口,只需run一下
*/
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
- 创建测试类, 测试类必须和启动类在同一个包下,或者是启动类所在的子包(后代包)
package com.zuoyueer.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Zuoyueer
* Date: 2019/12/16
* Time: 21:08
* @projectName Framework
* @description: 控制层
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("执行了...");
return "Hello Spring Boot .... !";
}
}
到此就配置完成了,点击运行启动类的main方法,看到如下启动信息说明启动成功
浏览器访问http://localhost:8080/hello
如果你希望访问其他包下的测试类,可以在启动类上加注解@ComponentScan(basePackages = {"com.zuoyueer"})
来指定包扫描路径,如果不指定默认就是扫描启动类所在的包
方式二: 骨架创建(推荐使用)
1.使用骨架新建工程或者module
后面的直接下一步,就完成创建了,创建好了目录结构如下
解释下目录:
- java包下就是源码了
- SpringbootApplication.java就是方式一中我们手写的启动类,使用骨架自动生成了
- resources是资源包
- static 是存储静态资源
- templates 是存储模板
- application.properties 是核心配置文件
- test 是测试目录
- 编写测试类
- 注意我把测试类放在了另外一个
com.zuoyueer.controller
包下,所以需要在启动类中增加@ComponentScan(basePackages = {"com.zuoyueer"})
注解
package com.zuoyueer.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Zuoyueer
* Date: 2019/12/16
* Time: 22:12
* @projectName Framework
* @description: 该控制类,和启动类在同一层目录下,或者在子目录下,才能访问到
* 如果不在同一目录下,那么需要在启动类上加@ComponentScan注解指定扫描的包
*/
@RestController
public class Hello {
@RequestMapping("/hello")
public String hello(){
System.out.println("执行了");
return "hello spring boot...真的难,但是还要坚持啊!......????";
}
}
- 运行启动类类的main方法, 和方式一中一样, 最后访问
http://localhost:8080/hello
可以看到访问测试类成功
方式三: 官网生成模板
- 访问官网https://start.spring.io/
- 写好了,点击绿色Cenerate 按钮,就可以下载模板了,下载并解压后的模板如下:
- 在idea中导入这个项目就可以和方式二一样使用了,这里就不再累述了
本文结束,感谢阅读