什么时候可以不用注解@Autowired
以前写代码@Autowired满天飞,最近在看Budapest人写的测试代码,发现他们的代码长这样:
public class Gateway {
private final GatewayProperties gatewayProperties;
public String url(final String subdomain, final String path) {
Assert.notNull(path, "the path must not be null");
Assert.isTrue(StringUtils.isEmpty(path) || path.charAt(0) == '/', "the path must start with a '/'");
final String host = StringUtils.isEmpty(subdomain) ? gatewayProperties.host : subdomain + "." + gatewayProperties.host;
return String.format("%s://%s%s", gatewayProperties.scheme, host, path);
}
}
注意到 private final GatewayProperties gatewayProperties; 这一行没有用到注解@autowired,再去查看GatewayProperties这个类:
@Data
@Configuration
@ConfigurationProperties(prefix = "gateway")
public class GatewayProperties {
String scheme;
String host;
...
它有个注解@Data成功引起了我的注意。
@Data是lombok的一个注解,它主要用来做什么的呢?
@Data
All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!
那么重点是注解@RequiredArgsConstructor又是干嘛的呢?官网解释:
Generates constructor that takes one argument per final / non-null field.
所以它会为final和nonnull的属性作为参数产生一个构造函数。
有个构造函数就这么厉害了?!
然后再去翻spring的官方解释:
Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
Regarding the default constructor: You either need the default constructor, a constructor with the Autowired annotation when you have multiple constructors, or only one constructor in your class with or without the Autowired annotation.
结论就是这样的: If a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
看来以后不用autowired满天飞了。
以上。