目录
1、项目入口类 - SpringBootDemoApplication
2、了解核心注解 - @SpringBootApplication
1、https://start.spring.io 初始化错误
2、连接失败 Request failed with status code 403
2、通过http://patorjk.com/software/taag网站生成字符
3、启动浏览器,访问http://localhost:8888/welcome
2、在resources目录里创建spring-config配置文件
3、启动项目,访问http://localhost:8888/toLogin
一、Spring Boot基本配置
(一)入口类与@SpringBootApplication
利用Spring Initializr
创建Spring Boot
项目
项目基本信息配置
添加依赖
全部依赖
设置项目名及保存位置
1、项目入口类 - SpringBootDemoApplication
- 包含一个主方法作为入口类的入口方法
- 利用SpringApplication类的静态方法
run()
启动入口类实例,可以接收命令行参数
2、了解核心注解 - @SpringBootApplication
- @SpringBootApplication是Spring Boot的核心注解,是一个组合注解。
3、设置exclude属性值,关闭特定的自动配置
-
关闭数据源自动配置
-
(二)创建SpringBoot项目报错
1、https://start.spring.io 初始化错误
2、连接失败 Request failed with status code 403
解决办法1 修改Http Proxy配置
成功
解决办法2 修改项目URL地址
将https://start.spring.io/ 改为 http://start.spring.io/
成功
(三)启动项目,查看效果
必须暂时关闭数据源自动配置(因为目前尚未配置数据源,不关闭数据源自动配置,运行程序要报错)
运行时如果报错jdk发行版本无效,是因为jdk版本不一致导致的,可自行检查setting设置
(四)添加控制器与路由函数
-
直接在入口类上面添加
@Controller
注解,然后定义路由函数index()
package net.ydl.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.sql.DataSource;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})// 不采用数据源自动配置
@Controller
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
@RequestMapping("/")
@ResponseBody
public String index() {
return "<h3>Welcome to Spring Boot World~</h3>";
}
}
启动项目,访问http://localhost:8080
如果出现无法访问的错误
双击tomcat\bin目录下的startup.bat,关闭服务
解决办法选择一致的JDK版本
添加路由函数welcome()
,通过model
参数向前端模板页面传递数据
@GetMapping("/welcome")
public String welcome(Model model) {
//通过model向模板页面传递数据
model.addAttribute("message","Dear Friends, Welcome to Spring Boot World~");
return "welcome"; //逻辑视图名
}
在templates
里创建welcome.html
,跟路由函数welcome()
里的逻辑视图名welcome
相对应,其中<span>
元素的内容是静态数据,客户端打开页面看到的数据
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<head>
<body>
<h3><span th:text="${message}">亲爱的朋友,欢迎访问Spring Boot世界~</span></h3>
</body>
</html>
运行welcome.html文件
启动welcome.html
项目 ,看到后端控制器通过model
传递过来的数据
(五)定制关闭Banner
1、在resources目录下创建banner.txt文件
2、通过http://patorjk.com/software/taag网站生成字符
3、将网站生成的字符复制到banner.txt文件里
4、启动应用程序
5、关闭Banner
- 修改入口程序代码
启动应用,项目启动图案消失
注释掉设置旗帜模式语句,恢复启动图案
(六)使用Spring Boot的应用属性文件进行配置
1、修改服务器的端口号
在application.properties文件里修改端口号为8888