IntelliJ IDEA中@Autowired注入報錯 and Mybatis 3.5新特性——Optional

方法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;
    @Autowired
    public 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 {
    @Autowired
    private 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!"));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章