Spring Boot之省略注入

Spring提供的标注,其基于容器自动寻找和加载特定的对象。

其寻找和匹配的范围包括: @Component, @Bean, @Service, @Repository, @Controller等声明的对象。使用方式@Autowired可以用在属性、方法和构造函数上。

查看其定义如下:@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Autowired {    /** * Declares whether the annotated dependency is required. *Defaults to {@code true}. */ boolean required() default true; }

基于其标注定义,可以知道其使用的Target如上所示,几乎适用于各个场景。 某些场景下的省略 以下是基于构造方法的加载: package com.example.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; @Autowired public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }

以下是等价的自动加载方式: @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }

根据其官方说明 If a bean has one constructor, you can omit the @Autowired 于是这里就可以省略@Autowired。 还有其他类似省略的注入情况吗? 有,当然有,Java初高级一起学习分享,喜欢的话可以我的学习群64弍46衣3凌9,或加资料群69似64陆0吧3基于@Bean注解方法之时,如果方法中有参数的话,则自动进行注入加载。 示例如下: @Configuration class SomeConfiguration { @Bean public SomeComponent someComponent(Depend1 depend1, @Autowired(required = false) Depend2 depend2) { SomeComponent someComponent = new SomeComponent(); someComponent.setDepend1(depend1); if (depend2 != null) { someComponent.setDepend2(depend2); } return someComponent; } }

在上述示例中,Depend1是自动注入的, Depend2是可选的注入,为了使用required=false的设置,则这里使用了@Autowired,默认情况下是无需使用的。 总结 在实际使用和开发中,需要注意构造方法以及@Bean方法调用的自动注入情况

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值