关于springboot:聊聊Spring中的Autowired注解

2次阅读

共计 1619 个字符,预计需要花费 5 分钟才能阅读完成。

明天来跟大家聊聊简略聊聊 @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 {

@Autowired
public 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 代替。
以上,轻易写写,谢谢大家的观看。

正文完
 0