@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {
private final JdbcTemplate jdbcTemplate;
...
}
@AllArgsConstructor是Lombok中的一个注解,其功能是生成一个为类中所有非static变量以及未初始化的final变量进行赋值的构造函数,生成的class文件中的代码如下:
@Repository
public class UserRepositoryImpl implements UserRepository {
private final JdbcTemplate jdbcTemplate;
...
public UserRepositoryImpl(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
这个生成的构造函数没有使用@Autowired注解,但却能够成功运行。
网上搜了一下原因,按照官方文档的说法,如果一个bean有一个构造器,就可以省略@Autowired。
If a bean has one constructor, you can omit the @Autowired
省略@Autowired配合Lombok,能够有效减少代码长度,可能对于初学者有点不太直观,但是习惯了之后就会觉得很舒服。
使用@AllArgsConstructor为final变量自动生成构造器的话,idea中代码会一直飘红报错,idea中安装lombok plugin插件就能够避免这种情况,能够识别自动生成的代码。