3、@Autowired是什么

答:@Autowired表示某个属性是否需要进行依赖注入,一般是写在属性上,也可以写在方法上。

在Spring容器初始化的过程中,到了属性填充这一步,会给加了@Autowired的注解属性,自动赋值

该注解是先根据类型去Spring容器中找出该类型所有的bean对象,如果找出多个则再根据属性的名字

从多个中再确定一个,如果required属性为true,并且根据属性信息找不到对象,则直接抛异常。

 

扩展:

1、试试@Autowired加在方法上或者构造方法上。

2、什么是根据类型去匹配,TestService里面的TestService接口属性对象加了@Autowired注解,

这个TestServiceImpl1和这个TestServiceImpl2,这两个就是TestService类型。

3、看看Autowired注解的代码:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

    /**
     * Declares whether the annotated dependency is required.
     * <p>Defaults to {@code true}.
     */
    boolean required() default true;

}

4、可以配合@Qualifier注解去使用

posted @ 2021-12-29 18:33  正能量教官  阅读(826)  评论(0编辑  收藏  举报