首先創建一個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());
}
}