目录
1.1.1 使用@ConfigurationProperties获取配置文件内容
1.1.2 使用 @PropertySource(value = {"classpath: person.properties"})读取指定配置文件内容
1.1.4 使用 @ImportResource 导入 spring 的配置文件
一、配置文件
1.1 配置文件读取方式
1.1.1 使用@ConfigurationProperties获取配置文件内容
@ConfigurationProperties(prefix = "person") 代表配置文件中前缀内的数据内容
由于必须是组件这个 @ConfigurationProperties 才会生效,故要加上 @Component
@Component
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
1.1.2 使用 @PropertySource(value = {"classpath: person.properties"})读取指定配置文件内容
@PropertySource 需要和 @ConfigurationProperties 配合使用
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person implements Serializable {
。。。。
}
1.1.3 使用 @Value 读取指定内容
只需要把当前实体类加入到容器中,即可以用 SpEL 表达式获取 application.properties 中的参数
@Component
public class Person implements Serializable {
private static final long serivalVersionUID = 1L;
@Value("${person.last-name}")
private String lastName;
...
}
1.1.4 使用 @ImportResource 导入 spring 的配置文件
1.2 与 @Value 对比
@ConfigurationProperties | @Value | |
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持,只能取出基本类型数据 |
使用场景 | 专门写了一个 javaBean 来和配置文件进行映射时使用 | 只在某个业务逻辑中需要获取一个配置文件中的某项值,使用 @Value |
1.3 SpringBoot 推荐的配置类配置方式
SpringBoot 推荐使用 @Configuration 注解,实现全注解配置配置文件
config/MyAppConfig
/**
* 指明当前类是一个配置类,用来替代之前的spring配置文件
*/
@Configuration
public class MyAppConfig {
private String url;
/**
* 将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
* @return
*/
@Bean
public HelloService helloService() {
System.out.println("配置类中@Bean添加组件了");
url = "http://www.baidu.com";
return new HelloService();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
运行时,发现自动添加到容器中了
测试用例:
@Test
public void testHelloService() {
System.out.println(myAppConfig.getUrl());
}
1.4 多环境支持
1.4.1 properties 文件
选择 properties 文件做配置文件时,只需要使用 spring.profiles.active 指定当前的配置文件
如创建文件 application-dev.properties,application-prod.properties
// 主配置文件 application.properties 中
spring.profiles.active=prod
1.4.2 yml 文件
与 properties 文件不同,yml 文件的配置是在 application.yml 文件中,通过 --- 分块符区分模块,并用 spring.profiles.active 指定当前的配置文件
server:
port:8081
spring:
profiles:
active: prod
---
server:
port: 8086
spring:
profiles: dev
person:
lastName: 小张
age: 18
maps: {k1:v1, k2:v2}
---
server:
port: 8087
spring:
profiles: prod
person:
lastName: 小张333
age: 18
maps: {k1:v1, k2:v2}
1.4.3 使用 idea 配置直接指定
1.4.4 指定默认启动文件的路径(重要)
springboot 中可以通过 spring.config.location 指定默认的配置文件路径。可以在部署到服务器时,指定在 war 包外部存放的配置文件,实现只修改配置文件,不修改项目代码。
nohup java -jar ${CRTDIR}/imapi-socket-2.0.war --spring.config.location=${C
RTDIR}/application-local.properties,${CRTDIR}/application.properties --logging.config=${CRTDIR}/logback-spring.xml > /dev/null 2>&1 &
1.4.5 配置文件加载位置优先级
默认加载位置的顺序:
- -- file:./config/
- -- file:./
- -- classpath:/config/
- -- classpath:/
特性:
- 优先级从高到底的顺序,所有位置的文件都会被加载,可以实现互补配置
- 高优先级会覆盖低优先级配置的内容
1.4.6 配置项目的访问路径
使用 server.context-path 可以指定项目的访问路径
server.context-path = /boot
1.5 自动配置原理
二、日志框架
2.1 常见日志框架和选择
日志抽象框架:
- JCL
- SLF4j:与 Log4j 和 Logback 同源
- jboss-logging
日志实现框架:
- Log4j:存在性能问题
- JUL
- Log4j2:apache公司出品,但与其他框架的兼容性不足
- Logback
最终选择:
抽象框架: SLF4j 实现框架: Logback
2.2 SLF4j 的使用
2.2.1 如何让系统中所有的日志都统一到 slf4j
- 将系统中其他的日志系统都排除出去(去掉依赖)
- 用中间包替换原有的日志框架
- 导入slf4j其他的实现
2.2.2 日志输出格式
格式:
- %d: 表示日期时间
- %thread: 表示线程名
- %-5level: 级别从左显示5个字符宽度
- %logger{50}:表示 logger 名字最长50个字符,否则按照句点分割
- %msg: 日志消息
- %n:换行符
例子:
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} === [%thread] === %-5level === %logger{50} === %msg%n
2.2.3 自定义日志配置文件
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<!-- <property name="LOG_PATH" value="d:/logs"/>-->
<!--设置系统日志目录-->
<property name="APPDIR" value="app"/>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 日志记录器,日期滚动记录 -->
<appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/api.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/info/api-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式记录日志 -->
<append>true</append>
<!-- 日志文件的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{50} %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 此日志文件只记录info级别以上的 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<logger name="org.springframework.aop.aspectj" level="ERROR"/>
<logger name="org.mongodb" level="ERROR"/>
<logger name="io.netty" level="ERROR"/>
<logger name="org.redisson" level="ERROR"/>
<logger name="org.springframework" level="ERROR"/>
<logger name="org.tio.client.TioClient" level="ERROR"/>
<!-- <root level="DEBUG"> -->
<root level="INFO">
<appender-ref ref="FILEINFO"/>
<appender-ref ref="STDOUT"/>
</root>
</configuration>
三、SpringBoot 结合 web 项目
3.1 静态资源映射
3.1.1 默认映射路径
"classpath":"/META-INF/resources/",
"classpath":"/resources/",
"classpath":"/static/",
"classpath":"/public/",
"/":当前项目的根路径
浏览器默认图标路径:
resources/resources/favicon.icon
3.1.2 自定义静态资源映射路径
在 application.properties 配置文件中,配置:
spring.resources.static-locations=classpath:/hello,classpath:/data/
3.2 模板引擎
3.2.1 引入 Thymeleaf
<properties>
...
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>3.0.11</thymeleaf-layout-dialect.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2.2 Thymeleaf 语法
th:任意html属性;来替换原生属性的值,如:th:text;改变当前元素里面的文本内容;th:id th:class 等
Simple expressions:(表达式语法) Variable Expressions: ${...}:获取变量值;OGNL; 1)、获取对象的属性、调用方法 2)、使用内置的基本对象: #ctx : the context object. #vars: the context variables.
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5
#vars: the context variables. #locale : the context locale. #request : (only in Web Contexts) the HttpServletRequest object. #response : (only in Web Contexts) the HttpServletResponse object. #session : (only in Web Contexts) the HttpSession object. #servletContext : (only in Web Contexts) the ServletContext object. ${session.foo} 3)、内置的一些工具对象: #execInfo : information about the template being processed. #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax. #uris : methods for escaping parts of URLs/URIs #conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections. #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration). Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样; 补充:配合 th:object="${session.user}: <div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div> Message Expressions: #{...}:获取国际化内容 Link URL Expressions: @{...}:定义URL; @{/order/process(execId=${execId},execType='FAST')} Fragment Expressions: ~{...}:片段引用表达式 <div th:insert="~{commons :: main}">...</div> Literals(字面量) Text literals: 'one text' , 'Another one!' ,… Number literals: 0 , 34 , 3.0 , 12.3 ,… Boolean literals: true , false Null literal: null Literal tokens: one , sometext , main ,… Text operations:(文本操作) String concatenation: + Literal substitutions: |The name is ${name}| Arithmetic operations:(数学运算)
Binary operators: + , ‐ , * , / , %
3.2.3 使用
三、SpringBoot 数据库
3.1 使用 Druid 实现数据库操作
3.1.1 默认映射路径