過去在Sping框架中,我們都會習慣使用@Autowired的註解來注入一個Bean,如下

1.png

但是使用@Autowired的時候會發現IDE在註解下面出現黃黃的警告,

展開警告的詳細內容,可以看到上面寫著: "Field injection is not recommended "

也就是不建議使用欄位注入的方式

2.png

這邊引用了參考文章的解釋如下:

Field injection is not recommended, because the list of required dependencies are unclear during instance creation. This makes testing more difficult and could lead to runtime exceptions when the bean is instantiated without spring.

To clearly state the required dependencies of the class, they should be added to the constructor that has the @Autowired annotation. This way, these dependencies can be provided more easily through Spring's dependency injection mechanism.

 

這個黃黃的警告,實在是看了礙眼

因此我們可以改用建構子(Constructor)注入的方式來解除這個警告

首先先將變數都加上final的修飾詞,並且建立一個初始化的Constructor

3.png

當Spring執行中,就會自動地將Bean注入了

此外,我們可以使用Lombok來的@RequiredArgsConstructor來更簡化程式碼,使code看起來更簡潔乾淨

Lombox的@RequiredArgsConstructor註解介紹可以參考以下文章:

在Spring Boot 使用Lombok - @RequiredArgsConstructor、@NoArgsConstructor、@AllArgsConstructor

4.png

 

arrow
arrow

    Mark Zhang 發表在 痞客邦 留言(0) 人氣()