目录 CONTENTS
学习背景
这套笔记来自一个 Spring Boot 入门系列,参考的教程博客写于 2016 年,对应的 Spring Boot 版本较低,很多配置项在新版本里已经变化甚至废弃,但作为入门学习仍然够用。下面按天整理,并标注了哪些地方在新版本里需要注意。
Day 1:环境准备
Spring Boot 可以基于 Spring 轻松创建「可以运行」的、独立的、生产级应用程序,大多数 Spring Boot 应用只需要很少的 Spring 配置。做 Web 应用之前的准备:
- 安装 IntelliJ IDEA;
- 安装并配置 Java,配置环境变量:
JAVA_HOME D:\Java\jdk_8
CLASSPATH .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
Path %JAVA_HOME%\bin
- 安装并配置 Maven(下载 Binary zip archive,解压后配置环境变量):
M2_HOME D:\maven\apache-maven-3.5.3-bin\apache-maven-3.5.3
Path %M2_HOME%\bin
- 用 IDEA 创建 Spring Boot 工程,然后就可以开始写代码了。
参考文档:Spring Boot 中文文档、官方英文文档。
Day 2:入口类与自动配置
项目创建成功后会自动下载依赖。入口类在 src/main/java/包名/ 下,核心注解是 @SpringBootApplication,它的作用是开启 Spring Boot 的自动配置。加上 @RestController 这个类就变成了 Controller,再提供一个地址映射方法:
@RequestMapping(value = "/", produces = "text/plain;charset=UTF-8")
String index() {
return "Hello Spring Boot!";
}
运行后自动启动内嵌 Tomcat,浏览器访问 http://localhost:8080 即可看到输出。
@SpringBootApplication 是一个组合注解,源码里包含了三个注解:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
)})
public @interface SpringBootApplication {
}
@SpringBootConfiguration:表明这个类是一个配置类;@EnableAutoConfiguration:让 Spring Boot 根据类路径中的 jar 依赖为项目自动配置;@ComponentScan:告诉 Spring 哪些 package 下带注解的类会被自动扫描并装入 bean 容器。
因为系统会扫描入口类的同级包及下级包,所以建议把入口类放在 groupId + artifactId 组合的包名下。
如果只想让 @SpringBootApplication 扫描特定的类,可以关闭特定的自动配置:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
定制 Banner
启动时控制台默认输出的启动图案可以修改:在 src/main/resources 下新建 banner.txt,用 patorjk 的 TAAG 工具生成字符贴进去即可。也可以在 main 方法里把 Banner 模式设为 OFF:
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Test19SpringBoot2Application.class);
builder.bannerMode(Banner.Mode.OFF).run(args);
}
配置文件
Spring Boot 使用全局配置文件 application.properties 或 application.yml,放在 src/main/resources 下。修改 Tomcat 默认端口和访问路径(以下是 Spring Boot 1.x 风格属性,新版本中 server.context-path 已改为 server.servlet.context-path):
server.context-path=/helloboot
server.port=8081
属性注入与中文乱码
在 application.properties 里定义属性,再用 @Value 注入:
book.author=罗贯中
book.name=三国演义
book.pinyin=sanguoyanyi
@Value(value = "${book.author}")
private String bookAuthor;
@Value("${book.name}")
private String bookName;
中文不做特殊处理会乱码,需要在配置文件中补充编码设置:
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
并在 IntelliJ IDEA 中依次点击 File → Settings → Editor → File Encodings,把 Properties Files 的默认编码设为 UTF-8,勾选 Transparent native-to-ascii conversion。
类型安全的配置是把 properties 属性和一个 Bean 关联起来(新版 Spring Boot 已废弃 @ConfigurationProperties 的 locations 方法):
@Component
@ConfigurationProperties(prefix = "book", locations = "classpath:book.properties")
public class BookBean {
private String name;
private String author;
private String price;
// getter / setter 省略
}
在 Controller 里 @Autowired 注入这个 Bean 即可使用。
日志与 Profile
默认日志框架是 Logback,在 application.properties 里配置输出位置和级别:
logging.file=/path/to/log.log
logging.level.org.springframework.web=debug
多环境配置用 application-{profile}.properties 定义,再在 application.properties 里指定激活哪个:
spring.profiles.active=dev
例如 application-dev.properties 里写 server.port=8080,application-prod.properties 里写 server.port=8081,切换 spring.profiles.active 就能切换端口。
Day 3:手写一个自动配置
这一天的目标是理解自动配置的原理,自己动手实现一个简单的 starter:当项目中存在某个类时,系统自动配置这个类的 Bean,并且 Bean 的属性可以在 application.properties 中配置。
- 用
maven-archetype-quickstart创建一个 Maven 项目; - 添加 Spring Boot 自动配置依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
- 属性配置类:
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private static final String MSG = "world";
private String msg = MSG;
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
}
不设置时默认值是 world。
- 判断依据类(也可以是第三方类库里的类):
public class HelloService {
private String msg;
public String sayHello() { return "hello " + msg; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
}
- 自动配置类:
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
}
}
@ConditionalOnClass 判断 HelloService 是否在类路径中存在,存在且容器中没有该类的 Bean 时自动配置;@ConditionalOnProperty 指定属性要满足的条件。
- 注册配置:在
resources下新建META-INF/spring.factories(IDEA 里需要先把目录 Mark Directory as → Resource Root),内容如下,多个配置类用逗号隔开:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.HelloServiceAutoConfiguration
- 在项目中使用:把自动配置 Module 作为依赖引入,在入口类里注入
HelloService,application.properties中写hello.msg=...,运行后即可看到hello <自定义内容>的输出。
Day 4–5:Web 与模板引擎
Spring Boot 提供了 spring-boot-starter-web 来支持 Web 开发,它自带内嵌 Tomcat 和 SpringMVC 依赖。Spring Boot 提供多种模板引擎(FreeMarker、Groovy、Thymeleaf、Velocity、Mustache),官方推荐 Thymeleaf。
Thymeleaf 通过 ThymeleafAutoConfiguration 自动配置集成所需的 Bean,通过 ThymeleafProperties 配置前缀、后缀等。从源码可以看到默认值:
@ConfigurationProperties("spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
// ...
}
也就是说,HTML 页面要放在 resources/templates 下,默认后缀是 .html,需要时在 application.properties 中以 spring.thymeleaf 为前缀修改。
Day 5 的计划是创建一个依赖为 Web + Thymeleaf + MySQL 的 Spring Boot Web 项目。
Thymeleaf:五分钟上手标准方言
Thymeleaf 是可扩展的模板引擎框架,自带 Standard 和 SpringStandard 两套标准方言;SpringStandard 与 Standard 几乎相同,只是额外集成了 Spring MVC(例如用 Spring EL 求值而不是 OGNL)。标准方言在模板中以 th 前缀的属性出现,比如 <span th:text="...">。
五种表达式
${...}:变量表达式*{...}:选择表达式#{...}:消息(i18n)表达式@{...}:链接(URL)表达式~{...}:片段表达式
变量表达式在 Spring 环境中等同于 Spring EL(否则是 OGNL),例如 ${session.user.name},用在属性里就是 <span th:text="${book.author.name}">;在 th:each 里则把 ${books} 求值为迭代器:
<li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>
选择表达式作用在 th:object 选定的对象上,而不是整个上下文:
<div th:object="${book}">
<span th:text="*{title}">...</span>
</div>
消息表达式用于国际化,从 .properties 文件按 key 取文本,Spring 应用中会自动与 MessageSource 集成:
<th th:text="#{header.address.city}">...</th>
链接表达式用来构建 URL,并自动加上应用上下文,例如 @{/order/list} 会渲染成 /myapp/order/list;也支持带参数(@{/order/details(id=${orderId},type=${orderType})})、相对路径、服务器相关路径(~/contents/main)和协议相关路径(//static.example.com/res/initial)。
文字与操作
Thymeleaf 支持文字(字符串、数字、布尔、null、文字标记)、字符串连接(+)、文字替换(|The name is ${name}|)、算术运算(+ - * / % 和一元减号)、布尔运算(and、or、!/not)、比较(> < >=、<=,也可写 gt lt ge le)、相等(== !=,也可写 eq ne),以及条件运算符((if) ? (then)、(if) ? (then) : (else)、默认值 (value) ?: (defaultvalue))。
表达式预处理写在 __ 之间,例如 #{selection.__${sel.code}__}:先执行里面的变量表达式,再把结果当作最终表达式的组成部分。
基本属性
th:text 替换标签主体(th:text 里的内容只是原型展示用的占位文字),th:each 按表达式返回的数组或列表重复元素,还有一批直接对应 HTML 属性的 th: 属性:
<p th:text="#{msg.welcome}">Welcome everyone!</p>
<form th:action="@{/createOrder}">
<input type="button" th:value="#{form.submit}" />
<a th:href="@{/admin/users}">...</a>
</form>
Thymeleaf 与 Spring 集成
Thymeleaf 为 Spring 3.x/4.x 提供集成库 thymeleaf-spring3、thymeleaf-spring4,需要加入类路径。它让 Thymeleaf 成为 JSP 的全功能替代品:把 @Controller 的映射方法转发给 Thymeleaf 管理的模板、在模板中使用 Spring EL、表单与绑定/校验错误集成、从 Spring 管理的消息文件显示国际化消息、用 Spring 的资源解析机制解析模板。
Spring 标准方言由 org.thymeleaf.spring4.dialect.SpringStandardDialect 实现,它扩展自 StandardDialect,额外提供:用 Spring EL 求值 ${...} 和 *{...}、用 ${@myBean.doSomething()} 访问应用上下文中的 bean、表单属性 th:field/th:errors/th:errorclass、#themes.code(...) 和 #mvc.uri(...) 等。
一般情况下不要直接配置 TemplateEngine,而是用 SpringTemplateEngine,它会自动应用 SpringStandardDialect 并启用 Spring 的 MessageSource:
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
对应的 XML 配置方式笔记里也有记录,思路相同:templateResolver 设置前缀、后缀、模板模式和缓存开关,templateEngine 引用 resolver 并开启 SpringEL 编译器(Spring 4.2.4+ 可用,默认关闭以保证向后兼容)。
小结
五天的节奏是:先把开发环境搭起来(Day 1),再理解 @SpringBootApplication 这个组合注解背后的自动配置机制(Day 2),然后动手写一个最小的 starter 把条件装配走一遍(Day 3),最后落到 Web 与模板引擎上(Day 4–5)。需要提醒的是,笔记里的配置项(server.context-path、@ConfigurationProperties 的 locations、spring-boot-autoconfigure 1.4.2.RELEASE)都属于早期版本,跟着新版本实践时需要对照当时的官方文档调整。
来源:SpringBootLearning 学习笔记整理
本文作者
Administrator, 于
发布在 Yui的秘密小屋。
版权协议:
CC BY-NC-SA 4.0,转载请注明出处。
评论
Comments 0 条