目錄
-
- 1. 使用@Value方式注入
- 2. 類型安全的屬性注入
- 3. 靜态屬性注入
1. 使用@Value方式注入
因為Spring boot源自Spring,是以Spring Boot同樣可以使用[email protected]注解的方式進行屬性注入。
因為在application.properties檔案中主要存放系統配置。自定義的配置不建議放在該檔案中,是以我們可以自定義properties檔案來存放自定義配置。
1.1首先防止中文亂碼
在application.properties中添加如下代碼:
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
File -> Settings -> Editor -> File Encodings
将Properties Files (*.properties)下的Default encoding for properties files設定為UTF-8,将Transparent native-to-ascii conversion前的勾選上

1.2 配置檔案
例如:在resources目錄下,建立people.peoperties檔案
内容如下:
people.id=1
people.name=張三
people.gender=男
1.3 建立對應的實體類
這裡需要注意的是:啟動本項目時不會自動加載上面的配置檔案,是以我們需要使用@PropertySource來引入該配置檔案
如果是在XML配置,則需要通過以下方式引用該配置檔案
@Component
@PropertySource("classpath:people.properties")
public class People {
@Value("${people.id}")
private long id;
@Value("${people.name}")
private String name;
@Value("${people.gender}")
private String gender;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
建立Controller類進行測試
@RestController
public class ShowController {
@Autowired
People people;
@RequestMapping(value="/show",produces = "text/plain;charset=UTF-8")
public String show(){
return "名字:"+people.getName()+" "+"性别:"+people.getGender();
}
}
啟動項目,浏覽器通路,結果如下:
2. 類型安全的屬性注入
當工作量大時,采用Spring中的配置方式就很容易出錯。使用Spring Boot的@ConfigurationProperties(prefix="")就能有效解決這個問題
使用這個注解,将實體類修改,内容如下:
@Component
@PropertySource("classpath:people.properties")
@ConfigurationProperties(prefix="people")
public class People {
private long id;
private String name;
private String gender;
//省略Getter和Setter方法
通過引入@ConfigurationProperties(prefix=“people”)注解,啟動項目後,Spring容器中對應的資料就自動注入到對象的屬性中。
3. 靜态屬性注入
在Spring中不支援我們通過@Autowired注入對象給一個靜态變量,這是因為靜态變量屬于類的層次,而Spring的依賴注入是對象的層次,類的加載在Spring 的IoC容器産生對象之前。當我們像這樣寫的時候:
@Autowired
private static clazz clazz;
我們調用的時候就會抛出運作時異常java.lang.NullPointerException,。
那麼,怎麼可以實作給靜态屬性注入值呢?
因為Spring支援setter方法注入,我們可以在非靜态的setter方法注入靜态變量。如下:
@Component
@PropertySource("classpath:people.properties")
public class FileUtils{
private static long id;
@Value("${people.id}")
public void setId(long id) {
this.id = id;
}
}
如果需要注入對象,就需要在setter方法上添加@Autowired注解,實作步驟:
- 在類定義上要添加@Component注解, 告訴Spring這個類需要掃描
- setter方法上添加@Autowired注解
- setter方法定義不能添加static關鍵字,否則自動注入失敗
像這樣:
@Component
public class FileUtils{
private static StorageClient1 client1;
@Autowired
@Qualifier("storageClient1")
public void setClient1(StorageClient1 client1) {
FastDFSUtil.client1 = client1;
}
}