丢掉 @Autowired,@Resource 让代码更简洁。
一:目前使用最广泛的 @Autowired
默认的注入方式为 byType ,也就是根据类型匹配,当有多个实现时,则通过 byName 注入,也可以通过配合@Qualifier注解来显式指定name值,指明要使用哪个具体的实现类
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
}
二:Java JSR-250中提供的注解 @Resource
默认通过 byName 注入,如果没有匹配则通过 byType 注入
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Resource
private RoleMapper roleMapper;
}
三:构造器注入
@Service
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
private final RoleMapper roleMapper;
public UserServiceImpl(UserMapper userMapper, RoleMapper roleMapper) {
this.userMapper = userMapper;
this.roleMapper = roleMapper;
}
}
四:Lombok提供的 @RequiredArgsConstructor
方式(会生成一个包含常量,和标识了NotNull的变量的构造方法)
也可写作 @RequiredArgsConstructor(onConstructor =@_(@Autowired))
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
private final RoleMapper roleMapper;
}