明天来跟大家聊聊简略聊聊@Autowired,Autowired翻译过去为主动拆卸,也就是主动给Bean对象的属性赋值。
@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;

}
复制代码
以上是@Autowired的定义,重点看 @Target,咱们发现@Autowired能够写在:

ElementType.CONSTRUCTOR:示意能够写在构造方法上

ElementType.METHOD:示意能够写在一般办法上

ElementType.PARAMETER:示意能够写在办法参数前

ElementType.FIELD:示意能够写在属性上

ElementType.ANNOTATION_TYPE:示意能够写在其余注解上

写在构造方法上
对于@Autowired写在构造方法上的状况,跟Spring抉择构造方法的逻辑无关,一个类中是不是有多个构造方法,是不是加了@Autowired注解,是不是有默认构造方法,跟构造方法参数类型和个数都有关系,前面独自来介绍。
写在一般办法上
对于@Autowired写在一般办法上的状况,咱们通常写的setter办法其实就是一个一般的setter办法,那非setter办法上加@Autowired会有作用吗?
比方:
@Component
public class UserService {

@Autowiredpublic void test(OrderService orderService) {    System.out.println(orderService);}

}
复制代码
这个test办法会被Spring主动调用到,并且能打印出OrderService对应的Bean对象。
写在办法参数前
把@Autowired写在参数前没有多大意义,只在spring-test中有去解决这种状况,源码正文原文:
Although @Autowired can technically be declared on individual method or constructor parameters since Spring Framework 5.0, most parts of the framework ignore such declarations. The only part of the core Spring Framework that actively supports autowired parameters is the JUnit Jupiter support in the spring-test module
写在属性上
这种状况不必多说了,值得注意的是,默认状况下,因为@Autowired中的required属性为true,示意强制依赖,如果更加某个属性找不到所依赖的Bean是不会赋null值的,而是会报错,如果把required属性设置为false,则会赋null值。
写在其余注解上
比方咱们能够自定义要给注解:
@Autowired
@Retention(RetentionPolicy.RUNTIME)
public @interface HoellerAutowired {
}
复制代码
@HoellerAutowired和@Autowired是等价的,能用@Autowired的中央都能够用@HoellerAutowired代替。
以上,轻易写写,谢谢大家的观看。