戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
spring应用手册(第二部分)
查看**@Autowired**注解源码: package org.springframework.beans.factory.annotation; @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}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Documented public @interface Autowired { boolean required() default true; }我们会发现Autowired有属性required,默认是true。
@AutoWired注解和bean标签中的autoWired属性差不多,可以通知spring帮我们自动组装Bean,例如:
/** * @author 戴着假发的程序员 * * @description */ @Component public class ArticleService { @Autowired private IAutorDAO autorDAO; @Autowired private IArticleDAO articleDAO; public int save(String title){ String author = autorDAO.get(); System.out.println("ArticleService-save:"); System.out.println("author:"+author); return articleDAO.save(title); }; }@Autowired注解可以写在成员变量上方,当然那也可以写在对应的setter方法上。 当然如果没有setter方法,我们会发现spring依然可以帮我们注入这些属性。
@Autowired默认首先是按照类型注入的,如果在当前容器中找到了多个同种类型的bean,就按照名称注入,如果一个都没找到就抛异常。
当然我们也可以通过修改属性required为false,通过spring如果找不到就组装。