CTO 说,再用错@Autowired 和@Resource 就可以领盒饭了
相关阅读:2T架构师学习资料干货分享
作者:liuxuzxx
@Autowire
private JdbcTemplate jdbcTemplate;
提示的警告信息
Field injection is not recommended Inspection info: Spring Team recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".
如图
基于构造函数的依赖注入
public class UserServiceImpl implents UserService{
private UserDao userDao;
public UserServiceImpl(UserDao userDao){
this.userDao = userDao;
}
}
基于Setter的依赖注入
public class UserServiceImpl implents UserService{
private UserDao userDao;
public serUserDao(UserDao userDao){
this.userDao = userDao;
}
}
基于字段的依赖注入
public class UserServiceImpl implents UserService{
private UserDao userDao;
}
如图
对于有final修饰的变量不好使
掩盖单一职责的设计思想
public class VerifyServiceImpl implents VerifyService{
private AccountService accountService;
private UserService userService;
private IDService idService;
private RoleService roleService;
private PermissionService permissionService;
private EnterpriseService enterpriseService;
private EmployeeService employService;
private TaskService taskService;
private RedisService redisService;
private MQService mqService;
public SystemLogDto(AccountService accountService,
UserService userService,
IDService idService,
RoleService roleService,
PermissionService permissionService,
EnterpriseService enterpriseService,
EmployeeService employService,
TaskService taskService,
RedisService redisService,
MQService mqService) {
this.accountService = accountService;
this.userService = userService;
this.idService = idService;
this.roleService = roleService;
this.permissionService = permissionService;
this.enterpriseService = enterpriseService;
this.employService = employService;
this.taskService = taskService;
this.redisService = redisService;
this.mqService = mqService;
}
}
与Spring的IOC机制紧密耦合
无法对注入的属性进行安检
通过上面,我们可以看到,基于字段的依赖注入方式有很多缺点,我们应当避免使用基于字段的依赖注入.推荐的方法是使用基于构造函数和基于setter的依赖注入.对于必需的依赖项,建议使用基于构造函数的注入,以使它们成为不可变的,并防止它们为null。对于可选的依赖项,建议使用基于Setter的注入
评论