聊聊Spring中的@Autowired注解
今天来跟大家聊聊简单聊聊@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代替。
以上,随便写写,谢谢大家的观看。
相关文章
- Spring学习笔记(三)——Spring注解开发&spring与Junit整合测试
- Spring学习笔记(二十九)——SpringBoot Actuator指标监控
- 简单介绍一下spring bean的生命周期_Spring bean的生命周期
- Spring Boot + @Async = 王炸!!
- Spring中的注解 @RequestBody和@ResponseBody的使用和区别
- Spring AOP 切面@Around注解的具体使用
- Spring MVC注解Controller源码流程解析--映射建立
- 理论:第五章:Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点
- Spring几个注解比较说明
- GraphQL实践2——Spring-GraphQL集成JPA与MySQL
- Spring-通过注解注入Bean的几种方式(二)
- Spring-通过注解注入Bean的几种方式(一)
- spring mvc 返回json报406错误
- spring security 深度使用
- Spring-事务
- Spring Boot 注解大全,一键收藏!回城路上复习!
- GPT视角学习:spring注解『文末赠书:提供免费国内GPT链接』
- Spring Cloud LoadBalancer 的实战应用服务发现示例
- spring的AOP(四)—-Spring AOP 编程(Advisor)详解编程语言
- Spring之AOP Annotation方式详解编程语言
- Spring任务调度之Spring-Task详解编程语言
- Spring @Conditional注解的使用详解编程语言
- Spring Boot Starters启动器详解编程语言
- Spring Boot(十四):spring boot整合shiro-登录认证和权限管理详解编程语言
- spring boot集成mybatis 自动生成实体类和mapper文件、Dao层详解编程语言
- java spring boot Swagger2 构建api文档详解编程语言
- Spring MVC中@Controller和@RequestMapping注解详解
- Spring框架致力于搭建基于MSSQL的稳健开发体系(spring mssql)