springboot-配置文件和日志

304 阅读2分钟

这是我参与8月更文挑战的第24天,活动详情查看:8月更文挑战

配置文件

springBoot的配置文件有两种

image.png

properties

语法结构 key = value

service.port = 8081

如果使用properties和类绑定

// 加载指定配置文件
@PropertySource(value = "classpath:student.properties")
public class Student {
​
//   使用properties文件设置属性
   @Value("${student.name}")
    private String name;

yaml

语法结构 : key : 空格 value

空格的要求非常严格,垂直对齐,属性需要缩进

service:   port: 8081

对象

student: name: YY age: 22   行内写法 student1: {name: YY,age: 22}

数组

数组 pets:

  • cat
  • dog
  • pig ​ pets1: [cat,dog,pig]

属性赋值

pojo

//前提,这个类是组件
@Component
//将配置文件的每一个属性映射到这个组件中,将本类的所有属性和配置文件中的相关配置(student下的所有属性)对应绑定
@ConfigurationProperties(prefix = "student")
public class Student {
   private String name;
   private int age;

test

@SpringBootTest
class DemoApplicationTests {
   @Autowired
   Student student;
​
   @Test
   void contextLoads() {
       System.out.println(student.getAge());
  }
​
}

松散绑定

数据库字段名last-name 可以和 驼峰命名法lastName 自动绑定

private String LastName;

JSR303数据校验

需要先开启@validate数据校验

image.png

//数据校验

@Validated
public class Student {
    @Email(message = "📪error")
    private String name;
    }

多环境配

优先级

image.png

指定环境

多文件

image.png

springboot的多环境配置,可以选择激活哪一个
spring:
  profiles:
    active: test
---
server:
  port: 8083
spring:
  profiles: test
---
server:
  port: 8082
spring:
  profiles: work
---
server:
  port: 8084
spring:
  profiles: up

错误

  1. 把server 写成service 导致端口修改没有生效
  2. 单文件配置多环境时,文件名必须是

日志

使用log4j

1.依赖

所有starter中的logging都需要去掉,只要去掉其中一个,并把它放在最前面就可以了。

<dependency>
           <groupId>org.mybatis.spring.boot</groupId>
           <artifactId>mybatis-spring-boot-starter</artifactId>
           <exclusions>
               <exclusion>
                   <groupId>org.springframework.boot</groupId>
                   <artifactId>spring-boot-starter-logging</artifactId>
               </exclusion>
           </exclusions>

2.配置xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" monitorInterval="1800">
   <appenders>
       <Console name="consolePrint" target="SYSTEM_OUT">
           <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
       </Console>
   </appenders>
​
   <loggers>
       <!-- 将业务dao接口填写进去,并用控制台输出即可 -->
       <logger name="com.wocai.keyun.dao.bus" level="info" additivity="false">
           <appender-ref ref="consolePrint"/>
       </logger>
​
       <root level="info">
           <appender-ref ref="consolePrint" />
       </root>
   </loggers>
</Configuration>

3.配置路径

需要指定logging的xml文件路径,dao层接口的路径

logging.config=classpath:log4j2.xml logging.level.com.wocai.keyun.dao.bus = info mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl