您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何進(jìn)行spring@value注入配置文件值失敗的原因分析,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
今天我寫了一個(gè)system.propertities配置文件定義了一個(gè)變量host=localhost。
然后在spring 配置文件中加入了加載配置
在service中這樣寫
@Value("${host}") private static String host;
但是獲取不到,各種查資料,最后發(fā)現(xiàn)是static關(guān)鍵字的原因
spring@Value依賴注入是依賴set方法
set方法是普通的對(duì)象方法,static變量是類的屬性,沒(méi)有set方法;
在spring使用@Value從application.properties將值注入到變量中時(shí),遇到
了注入失敗和注入值為null兩種問(wèn)題。
1、查看maven依賴,
(如果生效,可不進(jìn)行后續(xù)步驟)
2、加入注釋@PropertySource(value = “classpath:/application.properties”)配置文件路徑。
(如果生效,可不進(jìn)行后續(xù)步驟)
3、將被注入變量作為構(gòu)造方法參數(shù)進(jìn)行輸入。
maven依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.1.3.RELEASE</version> </dependency>
config類
@Configuration //聲明properties文件位置 @PropertySource(value = "classpath:/application.properties") public class DemoConfig { private String name; //將@Value作為構(gòu)造函數(shù)參數(shù)注入 public DemoConfig(@Value("${book.name}") String name){ this.name = name; } public void output(){ System.out.println(name); } }
main
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { // SpringApplication.run(DemoApplication.class, args); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); DemoConfig service = context.getBean(DemoConfig.class); service.output(); } }
1、spring版本問(wèn)題,根據(jù)本人實(shí)驗(yàn),4.x以下版本會(huì)出現(xiàn)一些注入問(wèn)題。
2、沒(méi)有寫@PropertySource(value = “classpath:/application.properties”)注解,或路徑不對(duì)。
3、.properties文件沒(méi)有放在resources文件夾中。
1、除了springboot自帶的application.properties文件外,可以自己創(chuàng)建test.properties,導(dǎo)入其他自創(chuàng)屬性,并管理屬性。
看完上述內(nèi)容,你們對(duì)如何進(jìn)行spring@value注入配置文件值失敗的原因分析有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。