@Autowired 是一個注釋,它可以對類成員變量、方法及構造函數進行標注,讓 spring 完成 bean 自動裝配的工作。
@Autowired 默認是按照類去匹配,配合 @Qualifier 指定按照名稱去裝配 bean。
常見用法
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import blog.service.ArticleService; import blog.service.TagService; import blog.service.TypeService; @Controller public class TestController { //成員屬性字段使用 @Autowired,無需字段的 set 方法 @Autowired private TypeService typeService; //set 方法使用 @Autowired private ArticleService articleService; @Autowired public void setArticleService(ArticleService articleService) { this.articleService = articleService; } //構造方法使用 @Autowired private TagService tagService; @Autowired public TestController(TagService tagService) { this.tagService = tagService; } }
- Java 自學經歷
- Java 面試題 H5
- Java 面試題小程序