如何理解@Autowired?

@Autowired这个注解到底是不是自动装配,这个看似愚蠢的问题,却困扰了我许久。都已经很明显了autowired翻译就是"自动装配",还有什么疑惑呢?

确实,但是看了一些视频,发现有人说@Autowired并不是自动装配,并且我也认同,但是翻译明明就是自动装配啊!那该如何理解呢?下面仅仅是我的理解,不对望指正。

image-20220106225309974

上面是自动注入的四种模式,先看第一种:

“(Default) No autowiring. Bean references must be defined by ref elements. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.”

意为没有自动装配,在某个Bean中使用了@Autowired注解,获取到的自动装配模式仍为no,看下面一段代码:

@Component
public class Person {

   @Autowired
   private Dog dog;

   @Override
   public String toString() {
      return "Person{" +
            "dog=" + dog +
            '}';
   }
}

@Component
public class Dog {

	@Value("旺财")
	private String name;

	@Override
	public String toString() {
		return "Dog{" +
				"name='" + name + '\'' +
				'}';
	}
}
public static void main(String[] args) {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Config.class);
    Person person = annotationConfigApplicationContext.getBean(Person.class);
    System.out.println(person);
    GenericBeanDefinition beanDefinition =
        (GenericBeanDefinition) annotationConfigApplicationContext.getBeanDefinition("person");
    System.out.println(beanDefinition.getAutowireMode()); // 0 --> no

}

所以,疑惑点就在这里,明明是使用了@Autowired注解,而它的意思也为自动装配之意,但是装配模式还是no…

先说说我的理解: @Autowired是自动装配,是一种粒度更小的自动装配方式,针对于某个属性或构造方法等,而自动装配模式是针对于类的,也就是相当于类全局。


版权声明:本文为weixin_45775746原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。