方法1:若希望允许null值,为 @Autowired
注解设置required = false
方法2:用 @Resource
替换 @Autowired
方法3:在Mapper接口上加上@Repository注解
方法4:使用Lombok
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserService {private final UserMapper userMapper;
}
Lombok生成的代码是这样的:
@Service
public class UserService {private final UserMapper userMapper;@Autowiredpublic UserService(final UserMapper userMapper) {this.userMapper = userMapper;}
}
Mybatis 3.5新特性——Optional支持
@Mapper
public interface UserMapper {@Select("select * from user where id = #{id}")Optional<User> selectById(Long id);
}public class UserController {@Autowiredprivate UserMapper userMapper;@GetMapping("/{id:\\d+}") //使用正则指定Id为数字public User findById(@PathVariable Long id) {return this.userMapper.selectById(id).orElseThrow(() -> new IllegalArgumentException("This user does not exit!"));}
}