我可以将@Autowire(Spring-Context)用于Kotlin桌面应用程序吗?



我正在尝试将spring di用于kotlin-javafx桌面应用,但春季不向Lateinit属性注入bean。

这是我的入门班

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)
        }
    }   
}

这是我的春季类别

package config
@Configuration
@ComponentScan(basePackages = arrayOf("domain", "ui"))
open class SpringConfig {   
}

这是我想注入的豆子

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
        }
    }
}

可以查看gluonhq ignite和afterburner.fx。它们旨在为您的Javafx应用程序提供DI功能。我通常更喜欢第一个,因为它允许您注入您选择的任何DI框架。

带有IGNITE的简单应用程序配置将看起来像:

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 */
    }
}

最新更新