本材料整理自github https://github.com/lenve/javaboy-video-samples中的代码
1.基础配置
1.1 关于banner
1.1.1 开关
// SpringApplication.run(Sbdemo02Application.class, args);
SpringApplicationBuilder builder = new SpringApplicationBuilder(Sbdemo02Application.class);
SpringApplication build = builder.build();
//是否开启banner
build.setBannerMode(Banner.Mode.OFF);
build.run(args);
1.1.2 自定义banner(springboot启动欢迎字符)
- 可在如下网址进行个性化banner文字生成:
http://patorjk.com/software/taag/#p=display&f=Graffiti&t=zhangjinglong
- banner文件放置的位置如下图所示:
1.1.3 banner效果预览
1.2 启动类的不同写法
1.2.1 默认方式
@RestController
@SpringBootApplication
//@EnableAutoConfiguration
public class App {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
1.2.2 变体写法
@RestController
@EnableAutoConfiguration
public class App {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
原因是@SpringBootApplication注解包含了@EnableAutoConfiguration注解,只使用@EnableAutoConfiguration可以启动成功
1.3 配置项
1.3.1 profiles
激活配置
application.properties文件里面写入需要激活的环境配置
spring.profiles.active=prod
文件目录结构
application.properties
application-dev.properties
application-prod.properties
1.3.2 读取自定义properties文件数据,填充到类成员变量
@PropertySource注解设置properties文件的所在位置
@ConfigurationProperties(prefix = “book”)设置properties中的前缀,比之前的 @Value("${book.id}")
方式更加便捷。
在Spring容器产生实体时依据成员变量名称和properties文件中key进行匹配和初始化赋值。
@Component
@PropertySource("classpath:book.properties")
@ConfigurationProperties(prefix = "book")
public class Book {
// @Value("${book.id}")
private Long id;
// @Value("${book.name}")
private String name;
// @Value("${book.author}")
private String author;
//getter setter and tostring()...
}
1.3.3 其他web容器配置
众所周知,springboot采用了内嵌的tomcat容器。如果换用其他的web容器,该如何配置呢?
下面以Undertow容器为例进行配置。
- 修改pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除Tomcat依赖 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加 Undertow依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.配置web启动项
# 服务启动端口
server.port=8081
#上下文启动路径
server.servlet.context-path=/zjl
# Tomcat URL 的编码配置
server.tomcat.uri-encoding=UTF-8
1.3.4 yaml格式的配置
yaml格式可以配置复杂的数据结构,可以对应对象之间的复杂依赖初始化。如下图所示: