首先创建一个bean类,其中@Configuration
注解和@ComponentScan
注解是必须的,如果你写了前缀,那么就需要@ConfigurationProperties
注解
package com.dzy.utils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "dzy")
@ComponentScan(basePackages = "com.dzy.utils")
public class RootFolderUtils {
// 图片资源的存放位置
private String picFolder;
}
然后在配置文件,比如application.propertity中注入属性:
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 图片文件夹的位置
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dzy.pic-folder=file:E://csdn/
然后就可以使用了,比如我们写一个测试类
package com.dzy;
import com.dzy.utils.RootFolderUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LidarLabApplicationTests {
@Autowired
private RootFolderUtils folderUtils;
@Test
void contextLoads() {
System.out.println(folderUtils.getPicFolder());
}
}