任务要求
基于study-springboot工程下的study-springboot-chapter01模块,其他默认。
任务收获
- 知晓属性文件和yaml文件系统启动时,加载的优先级顺序
- 学会如何在Springboot中自定义属性
环境要求
- JDK1.8+
- MySQL8.0.27+
- Maven 3.6.1+
- IDEA/VSCode
工程目录要求
对应模块:study-springboot-chapter02
任务实施步骤如下:
1、 改造study-springboot-chapter01工程
在pom.xml文件中导入配置文件处理器,以后编写配置就有提示了
<!--导入配置文件处理器,以后编写配置就有提示了-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、在resources目录下新建config目录并新建文件名称为customproperties.properties
并写入如下内容:例如经常自定义上传图片和视频的路径,避免在代码中写死,造成后期不好维护。
在customproperties.properties加入内容如下:
#自定义属性
config.picpath=d:/upload/pic
config.videopath=d:/upload/video
#域名服务
config.serverdomain=http://www.budaos.com
3、com.cbitedu.springboot.config包路径下编写Java Bean类CustomProperties内容如下:
package com.cbitedu.springboot.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration//保证该类会被扫描到
@PropertySource("classpath:config/customconfig.properties") //定义了要读取的properties文件的位置
@ConfigurationProperties(prefix = "config")//读取前缀为config 的内容
public class CustomProperties {
private String picPath;
@Override
public String toString() {
return "CustomProperties{" +
"picPath='" + picPath + ''' +
", videoPath='" + videoPath + ''' +
", serverDomain='" + serverDomain + ''' +
'}';
}
public String getPicPath() {
return picPath;
}
public void setPicPath(String picPath) {
this.picPath = picPath;
}
public String getVideoPath() {
return videoPath;
}
public void setVideoPath(String videoPath) {
this.videoPath = videoPath;
}
public String getServerDomain() {
return serverDomain;
}
public void setServerDomain(String serverDomain) {
this.serverDomain = serverDomain;
}
private String videoPath;
private String serverDomain;
}
4、运行com.cbitedu.springboot.property下的CustomConfigTest,内容如下:
package com.cbitedu.springboot.property;
import com.cbitedu.springboot.config.CustomProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
//@EnableConfigurationProperties(CustomProperties.class)
public class CustomConfigTest {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomConfigTest.class);
@Autowired
CustomProperties customProperties;
@Test
public void testConfig(){
LOGGER.info("图片上传的路径为"+customProperties.getPicPath());
LOGGER.info("参数列表"+customProperties.toString());
}
}
执行单元测试类
5、小结获取属性文件中的属性
实验实训
改写工程,使用@Value这个注解来读取自定义属性文件的值