Springboot學習3--整合配置檔案
阿新 • • 發佈:2021-02-14
技術標籤:Springboot
[email protected]註解
properties檔案新增student屬性,使用時用@Value("${變數}")
server.port=8081 spring.datasource.username=root spring.datasource.password=talent spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis.configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mybatis.mapper-locations=classpath:mapping/*Mapping.xml student.name=李磊 student.age=20 student.sex=男 student.school=中學
@Value("${student.name}")
String name;
@RequestMapping("getValue")
public String getValue(){
return name;
}
[email protected]
@Value註解只能加一個變數上邊,如果有許多一個個加,比較繁瑣可以使用@ConfigurationProperties
使用方法:
1.加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
2實體類添加註解指定prefix
package com.demo.springlearn.entity; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties(prefix = "student") public class Student { String name; int age; String sex; String school; }
3.自動配置後獲取值
@Autowired
Student student;
@RequestMapping("getStudent")
public Student getStudent(){
return student;
}
配置檔案中文亂碼解決:
Properties線上轉換yml格式網址: