spring::lateinit属性userRepo尚未初始化

kjthegm6  于 2022-12-28  发布在  Spring
关注(0)|答案(1)|浏览(161)

数据表.kt

class DataTable(private val param: MultiValueMap<String, String>, private val searchField: Array<String>) {
    @Autowired
    private val userService: UserService = UserService()

    private fun getAllCnt(): Int {
        return userService.countAll()
    }

用户报告kt

@Repository
interface UserRepo: JpaRepository<User, Long> {
    @Query(value="SELECT COUNT(*) FROM users", nativeQuery=true)
    fun countAll(): Int
}

用户服务.kt

@Service
class UserService {
    @Autowired
    private lateinit var userRepo: UserRepo

    fun countAll(): Int {
        return userRepo.countAll()
    }
}

错误

lateinit属性userRepo尚未初始化
也许我不想定义userRepo,但是我不知道如何定义userRepo。

ovfsdjhp

ovfsdjhp1#

似乎没有必要使用lateinit
你试试这样修
变更前

@Service
class UserService {
    @Autowired
    private lateinit var userRepo: UserRepo

    fun countAll(): Int {
        return userRepo.countAll()
    }
}

之后

@Service
class UserService(
    private val userRepo: UserRepo
) {

    fun countAll(): Int {
        return userRepo.countAll()
    }
}

相关问题