我试图将Spring DI用于kotlin-javafx桌面应用程序,但Spring并没有将bean注入到lateinit属性中。
这是我的入门课程
package ui
@Component
class Starter : Application() {
override fun start(primaryStage: Stage?) {
val root : Parent = FXMLLoader.load(javaClass.getResource("/view/main.fxml"))
primaryStage?.title = "Title"
primaryStage?.scene = Scene(root)
primaryStage?.show()
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
AnnotationConfigApplicationContext(SpringConfig::class.java)
launch(Starter::class.java, *args)
}
}
}
这是我的Spring-config类
package config
@Configuration
@ComponentScan(basePackages = arrayOf("domain", "ui"))
open class SpringConfig {
}
这是我想要注入的bean
package domain
@Component
open class State {
private val coinsState = mapOf(Coin.SYS to CoinState(Coin.SYS))
fun setActiveForCoin(coin : Coin, isActive : Boolean) {
val coin = coinsState[coin]
if (coin == null) throw IllegalArgumentException("Coin $coin does not exist!")
coin.isActive = isActive
}
}
最后我的javafx控制器应该接收一个bean(自动创建控制器的实例,我只是在.fxml文件中设置他的名字)
package ui.controller
@Component
class CoinController {
@Autowired
private lateinit var state : State
@FXML
fun showConfirmDialog(actionEvent: ActionEvent) {
println(state)
val alert = Alert(AlertType.CONFIRMATION)
alert.title = "Confirmation Dialog"
alert.headerText = "Look, a Confirmation Dialog"
//alert.contentText = "Are you ok with this?"
val result = alert.showAndWait()
if (result.get() == ButtonType.OK) {
// ... user chose OK
} else {
// ... user chose CANCEL or closed the dialog
}
}
}
答案 0 :(得分:1)
查看GluonHQ Ignite和afterburner.fx。它们意味着为您的JavaFX应用程序提供DI功能。我通常更喜欢第一个,因为它允许你注入你选择的任何DI框架。
使用点燃的简单应用配置如下所示:
class Starter: Application() {
private val context = SpringContext(this) { listOf() /* collection of packages to scan for bean definitions */ }
@Autowired
private lateinit var loader: FXMLLoader
override fun start(primaryStage: Stage) {
context.init()
/* ... now your FXML controllers can use autowiring */
}
}