美文网首页Java 杂谈
Spring Boot之省略注入的情况总结

Spring Boot之省略注入的情况总结

作者: 代码墨白 | 来源:发表于2018-07-14 12:52 被阅读4次

    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方法调用的自动注入情况

    相关文章

      网友评论

        本文标题:Spring Boot之省略注入的情况总结

        本文链接:https://www.haomeiwen.com/subject/hypjpftx.html