首页 > 解决方案 > Kotlin 和 Spring(数据):自定义设置器

问题描述

我目前正在开发一个使用 Kotlin 编写的 Spring Boot 的项目。必须提到的是,我对 Kotlin 还是比较陌生,来自 Java。我有一个小型数据库,由一个用于查找文件的表组成。在这个数据库中,我存储了文件的路径(为了这个测试目的,它只是存储在项目的资源中)。

有问题的对象如下所示:

@Entity
@Table(name = "NOTE_FILE")
class NoteFile {

    @Id
    @GeneratedValue
    @Column(name = "id")
    var id: Int

    @Column(name = "note")
    @Enumerated(EnumType.STRING)
    var note: Note

    @Column(name = "instrument")
    var instrument: String

    @Column(name = "file_name")
    var fileName: String
        set(fileName) {
            field = fileName

            try {
                file = ClassPathResource(fileName).file
            } catch (ignored: Exception) {
            }
        }

    @Transient
    var file: File? = null
        private set

    constructor(id: Int, instrument: String, note: Note, fileName: String) {
        this.id = id
        this.instrument = instrument
        this.note = note
        this.fileName = fileName
    }

}

我创建了以下存储库,用于从数据库中检索此对象:

@Repository
interface NoteFileRepository : CrudRepository<NoteFile, Int>

以及以下服务:

@Service
class NoteFileService @Autowired constructor(private val noteFileRepository: NoteFileRepository) {

    fun getNoteFile(id: Int): NoteFile? {
        return noteFileRepository.findById(id).orElse(null)
    }

}

我遇到的问题是当我调用getNoteFile函数时,构造函数和构造的 NoteFile 对象的设置器都没有被调用。因此,该file字段保持为空,而我希望它包含一个值。解决此问题的一种方法是使用该fileName字段的值设置该字段,但这看起来很奇怪并且必然会导致问题:

val noteFile: NoteFile? = noteFileService.getNoteFile(id)
noteFile.fileName = noteFile.fileName

这样,setter 被调用并且该file字段得到正确的值。但这不是要走的路,如上所述。这里的原因可能是使用 Spring Data 框架,需要一个默认构造函数。我正在使用此处描述的必要 Maven 插件来让 Kotlin 和 JPA 一起工作。

当对象由 Spring (Data) / JPA 框架构造时,是否有某种方式可以调用构造函数和/或 setter?或者也许我应该fileName在检索对象的服务中显式调用 setter ?或者这里最好的做法是将file字段作为一个整体删除并简单地将其转换为获取文件并像这样返回它的函数?

标签: springspring-bootkotlinspring-data-jpasetter

解决方案


推荐阅读