SpringBoot摒弃XML配置方式,改为全注解驱动
@Configuration
、@SpringBootConfiguration
@Bean
、@Scope
@Controller
、@Service
、@Repository
、@Component
@Import
@ComponentScan
步骤:
1、@Configuration 编写一个配置类
2、在配置类中,自定义方法给容器中注册组件。配合@Bean
3、或使用@Import 导入第三方的组件
如果注解指定的条件成立,则触发指定行为
@ConditionalOnXxx
@ConditionalOnClass
:如果类路径中存在这个类,则触发指定行为
@ConditionalOnMissingClass
:如果类路径中不存在这个类,则触发指定行为
@ConditionalOnBean
:如果容器中存在这个Bean(组件),则触发指定行为
@ConditionalOnMissingBean
:如果容器中不存在这个Bean(组件),则触发指定行为
例如:@ConditionalOnBean(value=组件类型,name=组件名字)
:判断容器中是否有这个类型的组件,并且名字是指定的值
@ConditionalOnRepositoryType
(org.springframework.boot.autoconfigure.data)
@ConditionalOnDefaultWebSecurity
(org.springframework.boot.autoconfigure.security)
@ConditionalOnSingleCandidate
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnWebApplication
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnWarDeployment
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnJndi
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnResource
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnExpression
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnClass (org.springframework.boot.autoconfigure.condition)
@ConditionalOnEnabledResourceChain
(org.springframework.boot.autoconfigure.web)
@ConditionalOnMissingClass (org.springframework.boot.autoconfigure.condition)
@ConditionalOnNotWebApplication
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnProperty
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnCloudPlatform
(org.springframework.boot.autoconfigure.condition)
@ConditionalOnBean (org.springframework.boot.autoconfigure.condition)
@ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition)
@ConditionalOnMissingFilterBean
(org.springframework.boot.autoconfigure.web.servlet)
@Profile
(org.springframework.context.annotation)
@ConditionalOnInitializedRestarter
(org.springframework.boot.devtools.restart)
@ConditionalOnGraphQlSchema
(org.springframework.boot.autoconfigure.graphql)
@ConditionalOnJava
(org.springframework.boot.autoconfigure.condition)
@ConfigurationProperties
: 声明组件的属性和配置文件哪些前缀开始项进行绑定@EnableConfigurationProperties
:快速注册注解:
@Component
、@ConfigurationProperties
注解,也没用。因为组件都扫描不进来,此时使用这个注解就可以快速进行属性绑定并把组件注册进容器将容器中任意组件(Bean)的属性值和配置文件的配置项的值进行绑定
- 1、给容器中注册组件(
@Component
、@Bean
)- 2、使用
@ConfigurationProperties
声明组件和配置文件的哪些配置项进行绑定
解决痛点:SpringBoot 集中化管理配置,application.properties
。配置多以后难阅读和修改,层级结构辨识度不高
特点:
- 设计目标,就是方便人类读写
- 层次分明,更适合做配置文件
- 使用
.yaml
或.yml
作为文件后缀
支持的写法:
@Component
@ConfigurationProperties(prefix = "person") //和配置文件person前缀的所有配置进行绑定
@Data //自动生成JavaBean属性的getter/setter
//@NoArgsConstructor //自动生成无参构造器
//@AllArgsConstructor //自动生成全参构造器
public class Person {
private String name;
private Integer age;
private Date birthDay;
private Boolean like;
private Child child; //嵌套对象
private List<Dog> dogs; //数组(里面是对象)
private Map<String,Cat> cats; //表示Map
}
@Data
public class Dog {
private String name;
private Integer age;
}
@Data
public class Child {
private String name;
private Integer age;
private Date birthDay;
private List<String> text; //数组
}
@Data
public class Cat {
private String name;
private Integer age;
}
properties表示法
person.name=张三
person.age=18
person.birthDay=2010/10/12 12:12:12
person.like=true
person.child.name=李四
person.child.age=12
person.child.birthDay=2018/10/12
person.child.text[0]=abc
person.child.text[1]=def
person.dogs[0].name=小黑
person.dogs[0].age=3
person.dogs[1].name=小白
person.dogs[1].age=2
person.cats.c1.name=小蓝
person.cats.c1.age=3
person.cats.c2.name=小灰
person.cats.c2.age=2
yaml表示法
person:
name: 张三
age: 18
birthDay: 2010/10/10 12:12:12
like: true
child:
name: 李四
age: 20
birthDay: 2018/10/10
text: ["abc","def"]
dogs:
- name: 小黑
age: 3
- name: 小白
age: 2
cats:
c1:
name: 小蓝
age: 3
c2: {name: 小绿,age: 2} #对象也可用{}表示
-
来表示驼峰命名|
开头,大文本写在下层,保留文本格式,换行符正确显示>
开头,大文本写在下层,折叠换行符---
可以把多个yaml文档合并在一个文档中,每个文档区依然认为内容独立application-{profile}.properties/yml
,用来指定多个不同的环境版本;默认使用application
主配置文件,通过spring.profiles.active=dev
激活指定的配置文件简化JavaBean 开发。自动生成构造器、getter/setter、自动生成Builder模式等
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<scope>compilescope>
dependency>
commons-logging
作为内部日志,但底层日志实现是开放的。可对接其他日志框架。jul
,log4j2
,logback
。SpringBoot 提供了默认的控制台输出配置,也可以配置输出为文件。logback
是默认使用的。SpringBoot怎么把日志默认配置好的:
spring-boot-starter
spring-boot-starter-logging
logback
+ slf4j
组合作为默认底层日志xxxAutoConfiguration
是系统启动好了以后放好的组件,后来用的。ApplicationListener
。logging
开始的所有配置。2023-06-07T22:18:12.568+08:00 INFO 7700 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-07T22:18:12.569+08:00 INFO 7700 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
默认输出格式:
ERROR
, WARN
, INFO
, DEBUG
, or TRACE
.注意: logback 没有FATAL
级别,对应的是ERROR
默认值:参照:spring-boot包additional-spring-configuration-metadata.json
文件
默认输出格式值:"defaultValue": "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"
以上配置使用的SpringBoot版本是:3.0.5
Logger logger = LoggerFactory.getLogger(getClass());
#或者使用Lombok的@Slf4j注解
由低到高:ALL
<TRACE
<DEBUG
< INFO
< WARN
< ERROR
<FATAL
<OFF
;
ALL
:打印所有日志TRACE
:追踪框架详细流程日志,一般不使用DEBUG
:开发调试细节日志INFO
:关键、感兴趣信息日志WARN
:警告但不是错误的信息日志,比如:版本过时ERROR
:业务错误日志,比如出现各种异常FATAL
:致命错误日志,比如jvm系统崩溃OFF
:关闭所有日志记录不指定级别的所有类,都使用root指定的级别作为默认级别
SpringBoot日志默认级别是 INFO
application.properties/yaml
中配置logging.level.=
指定日志级别level
可取值范围:TRACE
, DEBUG
, INFO
, WARN
, ERROR
, FATAL
or OFF
,定义在 LogLevel类中logger-name
叫root
,可以配置logging.level.root=warn
,代表所有未指定日志级别都使用 root 的warn
级别比较有用的技巧是:
将相关的logger
分组在一起,统一配置。SpringBoot 也支持。比如:Tomcat 相关的日志统一设置
logging.group.tomcat=org.apache.catalina,org.apache.coyote,org.apache.tomcat
logging.level.tomcat=trace
SpringBoot 预定义的两个组:
Name | Loggers |
---|---|
web | org.springframework.core.codec, org.springframework.http , org.springframework.web, org.springframework.boot.actuate.endpoint.web , org.springframework.boot.web.servlet.ServletContextInitializerBeans |
sql | org.springframework.jdbc.core, org.hibernate.SQL, org.jooq.tools.LoggerListener |
SpringBoot 默认只把日志写在控制台,如果想额外记录到文件,可以在application.properties
中添加logging.file.name
or logging.file.path
配置项。也可以直接在日志配置文件中直接指定
常用的logback-spring.xml
模板:
<configuration debug="false" scan="true" scanPeriod="1000 seconds">
<springProperty scope="context" name="spring.application.name" source="spring.application.name" defaultValue="app"/>
<timestamp key="date" datePattern="yyyyMMdd"/>
<property name="colorfulPattern"
value="%blue(%d{MM-dd HH:mm:ss}) [%boldYellow(%thread)] | %highlight(%-5level) | %boldGreen(%logger) %X{clientIp} %X{operateId} - %highlight(%msg) %n"/>
<property name="defaultPattern"
value="%d{MM-dd HH:mm:ss} [%thread] | %-5level | %logger %X{clientIp} %X{operateId} - %msg %n"/>
<property name="log.base_path" value="E:\data\logs"/>
<property name="log.max.size" value="100MB"/>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${colorfulPattern}pattern>
encoder>
appender>
<appender name="trace.appender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base_path}/${spring.application.name}/trace.${spring.application.name}.logfile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${log.base_path}/archive/${spring.application.name}/trace.${spring.application.name}.%d{yyyyMMdd}.%i.log.zip
fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}maxFileSize>
timeBasedFileNamingAndTriggeringPolicy>
rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${defaultPattern}pattern>
layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACElevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
appender>
<appender name="info.appender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base_path}/${spring.application.name}/info.${spring.application.name}.logfile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${log.base_path}/archive/${spring.application.name}/info.${spring.application.name}.%d{yyyyMMdd}.%i.log.zip
fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}maxFileSize>
timeBasedFileNamingAndTriggeringPolicy>
rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${defaultPattern}pattern>
layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFOlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
appender>
<appender name="debug.appender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base_path}/${spring.application.name}/debug.${spring.application.name}.logfile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${log.base_path}/archive/${spring.application.name}/debug.${spring.application.name}.%d{yyyyMMdd}.%i.log.zip
fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}maxFileSize>
timeBasedFileNamingAndTriggeringPolicy>
rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${defaultPattern}pattern>
layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUGlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
appender>
<appender name="error.appender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base_path}/${spring.application.name}/error.${spring.application.name}.logfile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${log.base_path}/archive/${spring.application.name}/error.${spring.application.name}.%d{yyyyMMdd}.%i.log.zip
fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}maxFileSize>
timeBasedFileNamingAndTriggeringPolicy>
rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${defaultPattern}pattern>
layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERRORlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
appender>
<appender name="trace.async" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0discardingThreshold>
<queueSize>256queueSize>
<includeCallerData>trueincludeCallerData>
<appender-ref ref="trace.appender"/>
appender>
<logger name="cn.felord.common.http.RestBodyAdvice" level="TRACE"/>
<logger name="cn.felord.app.mapper" level="DEBUG"/>
<springProfile name="dev">
<logger name="org.springframework.security" level="TRACE" additivity="false" >
<appender-ref ref="stdout"/>
logger>
<logger name="org.springframework.security.oauth2" level="DEBUG" additivity="false" >
<appender-ref ref="stdout"/>
logger>
<logger name="org.springframework.web" level="TRACE" additivity="false" >
<appender-ref ref="stdout"/>
logger>
springProfile>
<root level="info">
<appender-ref ref="stdout"/>
<appender-ref ref="info.appender"/>
<appender-ref ref="debug.appender"/>
<appender-ref ref="error.appender"/>
<appender-ref ref="trace.async"/>
root>
configuration>
归档:每天的日志单独存到一个文档中。
切割:每个文件10MB,超过大小切割成另外一个文件。
logback
(SpringBoot 默认整合),可以通过application.properties/yaml
文件指定日志滚动规则。log4j2.xml
或log4j2-spring.xml
)配置项 | 描述 |
---|---|
logging.logback.rollingpolicy.file-name-pattern |
日志存档的文件名格式(默认值:${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz ) |
logging.logback.rollingpolicy.clean-history-on-start |
应用启动时是否清除以前存档(默认值:false ) |
logging.logback.rollingpolicy.max-file-size |
存档前,每个日志文件的最大大小(默认值:10MB ) |
logging.logback.rollingpolicy.total-size-cap |
日志文件被删除之前,可以容纳的最大大小(默认值:0B )。设置1GB则磁盘存储超过 1GB 日志后就会删除旧日志文件 |
logging.logback.rollingpolicy.max-history |
日志文件保存的最大天数(默认值:7 ) |
通常配置 application.properties
就够了。当然也可以自定义。比如:
日志系统 | 日志系统 自定义 |
---|---|
Logback | logback-spring.xml , logback-spring.groovy , logback.xml , or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
最佳工作实践:自己要写日志配置文件,配置文件名加上 xx-spring.xml
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-loggingartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-log4j2artifactId>
dependency>
log4j2支持XML、JSON、YAML和properties四种配置文件格式
application.properties
配置文件,就可以调整日志的所有行为。如果不够,可以编写日志框架自己的配置文件放在类路径下就行,比如logback-spring.xml
,log4j2-spring.xml
kafka
之类的中间件,这和SpringBoot没关系,都是日志框架自己的配置,修改配置文件即可slf4j-api
记录日志。不要再 System.out.println()
了