spring - 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
字段作为一个整体删除并简单地将其转换为获取文件并像这样返回它的函数?
解决方案
推荐阅读
- linux - NetworkManager 连接断开原因 -3 问题
- php - svg 编程,坐标搞砸了
- python - 在电子邮件正文中发送循环结果
- laravel - 在 aws 中部署 laravel 应用程序时出现 500 服务器错误
- c++ - VS 2017 & 2019 运行 c++ 真的很慢
- python - 如何将 Matlab 代码转换为 Python?
- r - 如何结合 Lapply() 和 dbListFields() 来获取 DATABASE 中每个表的所有列名?
- javascript - 视频html5结束时淡入图标
- ruby-on-rails - Mongo::Error::OperationFailure Unknown modifier: $pushAll 更新模型时(mongoid、angular、rails)
- php - jquery在while循环php中获取select2的数据属性