14.AutoWired的使用场景

本文深入探讨了Autowired在构造函数上的4种使用方法,包括电源类的创建、有参构造函数的重写及供电方法的调用,为Spring框架的使用者提供了实用的编码技巧。

一共4中Autowired的使用方法

1.使用在构造函数上

创建一个电源类

 重写有参构造函数

 调用供电方法

测试

private static final AnnotationMatcher AUTOWIRED_ANNOTATION_MATCHER = new AnnotationMatcher("@org.springframework.beans.factory.annotation.Autowired(true)"); @Override public String getDisplayName() { return "Remove the `@Autowired` annotation on inferred constructor"; } @Override public String getDescription() { return "Spring can infer an autowired constructor when there is a single constructor on the bean. " + "This recipe removes unneeded `@Autowired` annotations on constructors."; } @Override public TreeVisitor<?, ExecutionContext> getVisitor() { return Preconditions.check(new UsesType<>("org.springframework.beans.factory.annotation.Autowired", false), new JavaIsoVisitor<ExecutionContext>() { @Override public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx); int constructorCount = 0; for (Statement s : cd.getBody().getStatements()) { if (isConstructor(s)) { constructorCount++; if (constructorCount > 1) { return cd; } } } // Lombok can also provide a constructor, so keep `@Autowired` on constructors if found if (!FindAnnotations.find(cd, "@lombok.*Constructor").isEmpty()) { return cd; } // `@ConfigurationProperties` classes usually use field injection, so keep `@Autowired` on constructors if (!FindAnnotations.find(cd, "@org.springframework.boot.context.properties.ConfigurationProperties").isEmpty()) { return cd; } return cd.withBody(cd.getBody().withStatements( ListUtils.map(cd.getBody().getStatements(), s -> { if (!isConstructor(s)) { return s; } maybeRemoveImport("org.springframework.beans.factory.annotation.Autowired"); return (Statement) new RemoveAnnotationVisitor(AUTOWIRED_ANNOTATION_MATCHER).visit(s, ctx, getCursor()); }) )); } }); } 同理推断写法判断当前类中是否被包含 @Autowired 方式注入的字段
最新发布
07-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值