2.18 @Autowired注解

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

查看@Autowired注解源码:

1 package org.springframework.beans.factory.annotation;
2 
3 @java.lang.annotation.Target({java.lang.annotation.ElementType.CONSTRUCTOR, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
5 @java.lang.annotation.Documented
6 public @interface Autowired {
7     boolean required() default true;
8 }

 

我们会发现Autowired有属性required,默认是true。

@AutoWired注解和bean标签中的autoWired属性差不多,可以通知spring帮我们自动组装Bean,例如:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Component
 7 public class ArticleService {
 8     @Autowired
 9     private IAutorDAO autorDAO;
10     @Autowired
11     private IArticleDAO articleDAO;
12 
13     public int save(String title){
14         String author = autorDAO.get();
15         System.out.println("ArticleService-save:");
16         System.out.println("author:"+author);
17         return articleDAO.save(title);
18     };
19 }

@Autowired注解可以写在成员变量上方,当然那也可以写在对应的setter方法上。 当然如果没有setter方法,我们会发现spring依然可以帮我们注入这些属性。

@Autowired默认首先是按照类型注入的,如果在当前容器中找到了多个同种类型的bean,就按照名称注入,如果一个都没找到就抛异常。

当然我们也可以通过修改属性required为false,通过spring如果找不到就组装。

posted @ 2020-10-10 08:25  戴着假发的程序员0-1  阅读(126)  评论(0编辑  收藏  举报