springboot給自定義的bean注入屬性

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章