我最近开始使用Kotlin过期,并使用Kotlin开始了一个Spring Boot宠物项目。
我尝试将自定义用户域对象集成到Spring Security,因此希望实现UserDetails接口。
鉴于我的域用户对象如下:
import org.springframework.data.annotation.Id as DocumentId
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.userdetails.UserDetails
@Document
data class User(@DocumentId val id: String? = null,
val username: String = "",
val password: String = "",
val email: String = "",
val name: String? = null,
val surname: String? = null) : UserDetails {
override fun isCredentialsNonExpired(): Boolean = true
override fun isAccountNonExpired(): Boolean = true
override fun isAccountNonLocked(): Boolean = true
override fun getAuthorities(): MutableCollection<out GrantedAuthority> = AuthorityUtils.createAuthorityList("USER")
override fun isEnabled(): Boolean = true
}
我收到以下错误:
意外覆盖:以下声明具有相同的JVM signature(getUsername()Ljava / lang / String;):public final fun&lt; get-username&gt;():Kotlin.String,public abstract fun getUsername():Kotlin.String!
意外覆盖:以下声明具有相同的JVM signature(getPassword()Ljava / lang / String;):public final fun&lt; get-password&gt;():Kotlin.String,public abstract fun getPassword():Kotlin.String!
由于我的User类已经有方法getUsername():Kotlin.String也实现了方法getUsername():Kotlin.String! ?
除了在属性的getter和setter上使用@JvmName之外,我该如何解决这样的错误?
答案 0 :(得分:26)
这里的问题是,从Kotlin的角度来看,属性获取器不可能从超类型覆盖函数。要解决此问题,可以通过创建属性private
来阻止编译器生成getter,并手动从超类型实现所需的方法,例如:
data class User(
private val username: String = ""
...
): UserDetails {
override fun getUsername() = username
...
}