功能 | 说明 |
---|---|
Maven | 3.3+ |
JDK | 1.8+ |
Spring Boot | 2.1.14.RELEASE |
Spring Framework | 5.1.15.RELEASE |
添加 web 环境依赖java
<?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>org.example</groupId> <artifactId>springboot-learn</artifactId> <version>1.0-SNAPSHOT</version> <description>基于Spring Boot的案例</description> <packaging>jar</packaging> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.14.RELEASE</version> </parent> <dependencies> <!-- spring boot web 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
// @RestController 为组合注解,等同于 Spring中的:@Controller + @ResponseBody @RestController public class LearnController { @RequestMapping("/hello") public String hello() { return "你好 Spring Boot"; } }
@SpringBootApplication public class LearnApplication { public static void main(String[] args) { SpringApplication.run(LearnApplication.class, args); } }
问题:启动主程序类的位置是否能够随便放?web
运行项目主程序启动类LearnApplication类,启动成功后,能够看见默认端口为8080spring
页面输出为 “你好 Spring Boot”。apache
至此,构建Spring Boot项目就完成了。springboot
开发中,每当完成一个功能接口或业务方法编写后,一般须要借助单元测试验证功能是否正确。markdown
Spring Boot对单元测试提供了很好的支持,在使用是,直接在pom.xml文件中添加app
spring-boot-starter-test测试依赖启动器,能够经过相关注解实现单元测试。框架
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
// 测试启动类,并加载Spring Boot测试注解 @RunWith(SpringRunner.class) // 标记为Spring Boot单元测试类,并加载项目的ApplicationContext上下文环境 // classes 知道项目主程序启动类 @SpringBootTest(classes = LearnApplication.class) public class LearnApplicationTest { @Autowired private LearnController learnController; @Test public void test() { String hello = learnController.hello(); System.out.println(hello); } }
在开发过程当中,一般会对一段业务代码不断的操做修改,在修改以后每每要重启服务,有些服务须要加载好久才能启动成功,这种没必要要的重复操做极大的下降了程序开发效率。为此,Spring Boot框架专门提供了进行热部署的依赖启动器,用于进行项目热部署,无需手动重启项目。maven
<!-- 热部署依赖启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
选择IDEA工具界面【File】-【Settings】,打卡Compiler界面,勾选【Build project automatically】ide
点击 Apply 应用,以及OK保存。
在项目任意界面使用组合快捷键【Ctrl+Alt+Shift+/】打开Maintenance选项框,选中并打开Registry页面
列表中找到【compiler.automake.allow.when.app.running】,将该值Value进行勾选。用于指定IDEA工具在程序运行过程当中自动编译,最后单击【Close】按钮完成设置
启动项目,访问 http://localhost:8080/hello
修改 “你好” 为 “hello”
为了测试热部署的是否有效,接下来,在不关闭项目的状况下,将LearnController类中数据修改,并保存,查看控制台会发现项目可以自动构建和编译,说明热部署生效