-
准備配置文件
web.images-path=D:\\IdeaProjects\\images
-
在屬性上,加 @Value注解。
@Value("${web.images-path}") private String filePath;
-
#測試配置文件注入
test.domain=www.xdclass.net
test.name=springboot
import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Data @Component @PropertySource("classpath:application.properties") public class ServerSettings { //名稱 @Value("${test.name}") private String name; // 域名 @Value("${test.domain}") private String domain; }
另外 考慮 前綴取值的做法。
如果讀取配置文件失敗:
默認Spring框架實現會從聲明 @ComponentScan 所在的類的package進行掃描,來自動注入,因此啟動類最好放在根路徑下面,或者指定掃描包范圍。