当前位置: 代码迷 >> 综合 >> IntelliJ IDEA中@Autowired注入报错 and Mybatis 3.5新特性——Optional
  详细解决方案

IntelliJ IDEA中@Autowired注入报错 and Mybatis 3.5新特性——Optional

热度:55   发布时间:2023-12-26 19:58:36.0

方法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!"));}
}

 

  相关解决方案