繁体   English   中英

Spring Boot 中基于表达式的 Autowire(使用 Kotlin)

[英]Expression based Autowire in Spring Boot (with Kotlin)

情况

我正在尝试提出一种方法来有条件地加载一个 bean(基于 2 个属性或环境变量的存在),如果它们丢失,则加载另一个 bean。

瓦尔斯

所以这两个属性(或环境变量)是:

  • ProtocolHOST
  • ProtocolPORT

因此,例如java -jar xxxx -DProtocolHost=myMachine -DProtocolPort=3333将使用我想要的 bean,但如果两者都丢失,那么您将获得另一个 bean。

@Component("Protocol Enabled")
class YesBean : ProtocolService {}

@Component("Protocol Disabled")
class NoBean : ProtocolService {

后来在我的控制器中,我有一个:

@Autowired
private lateinit var sdi : ProtocolService

所以我研究了多种选择:

同时使用@ConditionalOnProperty@ConditionalOnExpression ,我似乎无法取得任何进展。

我很确定我需要走Expression路线,所以我写了一些似乎失败的测试代码:

@PostConstruct
fun customInit() {
    val sp = SpelExpressionParser()
    val e1 = sp.parseExpression("'\${ProtocolHost}'")
    println("${e1.valueType}   ${e1.value}")
    println(System.getProperty("ProtocolHost")
}

返回:

类 java.lang.String ${ProtocolHost} 炸玉米饼

所以我不确定我的SPeL解析是否正常工作,因为它看起来只是返回字符串“${ProtocolHost}”而不是处理正确的值。 我假设这就是我在表达式语言中所做的所有尝试都失败的原因 - 这也是为什么我被卡住的原因。

任何援助将不胜感激!

谢谢

更新

我确实通过执行以下操作来解决问题

在我的主要:

 val protocolPort: String? = System.getProperty("ProtocolPort", System.getenv("ProtocolPort"))
 val protocolHost: String? = System.getProperty("ProtocolHost", System.getenv("ProtocolHost"))

 System.setProperty("use.protocol", (protocolHost != null && protocolPort != null).toString())
 runApplication<SddfBridgeApplication>(*args)

然后在bean定义上:

@ConditionalOnProperty(prefix = "use", name = arrayOf("protocol"), havingValue = "false", matchIfMissing = false)

@ConditionalOnProperty(prefix = "use", name = arrayOf("protocol"), havingValue = "false", matchIfMissing = false)

然而,这感觉就像一个黑客,我希望它可以直接在 SpEL 中完成,而不是提前设置变量。

这听起来像是基于 Java 的 bean 配置的完美用例:

@Configuration
class DemoConfiguration {

    @Bean
    fun createProtocolService(): ProtocolService {
        val protocolPort: String? = System.getProperty("ProtocolPort", System.getenv("ProtocolPort"))
        val protocolHost: String? = System.getProperty("ProtocolHost", System.getenv("ProtocolHost"))
        return if(!protocolHost.isNullOrEmpty() && !protocolPort.isNullOrEmpty()) {
            YesBean()
        } else {
            NoBean()
        }
    }

}

open class ProtocolService

class YesBean : ProtocolService()

class NoBean : ProtocolService()

您可能还想查看外部化配置以替换System.getProperty()System.getenv()

这看起来像这样:

@Configuration
class DemoConfiguration {

    @Bean
    fun createProtocolService(@Value("\${protocol.port:0}") protocolPort: Int,
                              @Value("\${protocol.host:none}") protocolHost: String): ProtocolService {
        return if (protocolHost != "none" && protocolPort != 0) {
            YesBean()
        } else {
            NoBean()
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM