想要在JAVA Bean中讀取配置文件中的內容有兩種方式,可以進行獲取到
第一種方式:
1、在默認的配置文件application.properties 中進行設置 Key-Value鍵值對
com.neusoft.duanml=Run SpringBoot
2、在需要使用的JAVA Bean中定義屬性,並且注解如下:
@Value("${com.neusoft.duanml}")
private String openSourceName;
3、在JAVA Bean中需要使用的地方進行引用,可以獲取到配置值
@RequestMapping("/openSourceName")
public String openSourceName() {
System.out.println(openSourceName);
return openSourceName;
}
第二種方式:
1、任意新建*.properties文件,設置KEY-VALUE鍵值對 如:resource.properties
com.itzixi.opensource.name=neusoft
com.itzixi.opensource.website=www.neusoft.com
com.itzixi.opensource.language=java
2、編寫具體的屬性對應JAVA Bean 來封裝配置文件*.properties中的屬性KEY-VALUE並進行配置如:Resource.java
1 package com.leecx.pojo; 2 3 import org.springframework.boot.context.properties.ConfigurationProperties; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.PropertySource; 6 7 @Configuration 8 @ConfigurationProperties(prefix="com.itzixi.opensource") 9 @PropertySource(value="classpath:resource.properties") 10 public class Resource { 11 12 private String name; 13 14 private String website; 15 16 private String language; 17 18 public String getName() { 19 return name; 20 } 21 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 public String getWebsite() { 27 return website; 28 } 29 30 public void setWebsite(String website) { 31 this.website = website; 32 } 33 34 public String getLanguage() { 35 return language; 36 } 37 38 public void setLanguage(String language) { 39 this.language = language; 40 } 41 42 43 44 }
其中在JAVA Bean中必須加上 三處注解如下:
@Configuration
@ConfigurationProperties(prefix="com.itzixi.opensource") prefix="com.itzixi.opensource" 為配置文件中的前綴變量值
@PropertySource(value="classpath:resource.properties") 為配置文件在項目的實際位置
注意事項:JAVA Bean中的屬性名稱 name、website、language必須為配置文件*.properties中@ConfigurationProperties(prefix="com.itzixi.opensource") prefix="com.itzixi.opensource" 去掉前綴的名稱
3、在具體的JAVA Bean中使用配置文件的屬性值:HelloController.java
1 package com.leecx.controller; 2 3 import java.util.Date; 4 5 import org.springframework.beans.BeanUtils; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.beans.factory.annotation.Value; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RestController; 10 11 import com.leecx.pojo.LeeJSONResult; 12 import com.leecx.pojo.Resource; 13 import com.leecx.pojo.User; 14 15 @RestController 16 public class HelloController { 17 18 @Autowired 19 private Resource resource; 20 21 @RequestMapping("/getResource") 22 public LeeJSONResult getResource() { 23 System.out.println(resource.getName()); 24 System.out.println(resource.getWebsite()); 25 System.out.println(resource.getLanguage()); 26 27 Resource bean = new Resource(); 28 BeanUtils.copyProperties(resource, bean); 29 return LeeJSONResult.ok(bean); 30 } 31 }
必須 通過注入IOC對象Resource 進來 , 才能在類中使用獲取的配置文件值。