如何在Kotlin伴生对象中使用@Value注入的变量?
问题:在Kotlin伴生对象中使用Spring注入的配置变量
我需要在类的伴生对象方法中使用通过@Value注入的配置变量openDateYmd,当前代码如下:
class EnumUtils( @Value("\${open-date}") lateinit var openDateYmd: String ) { companion object { fun getStatus(orderDate: LocalDateTime): Status { val openDateLocalDateTime = parseToLocalDateTime(openDateYmd) // 此处无法访问openDateYmd return when { orderDate.isBefore(openDateLocalDateTime) -> Status.VALUE_1 else -> Status.VALUE_1 } } } }
请问该如何实现?
解决方案
方法一:通过实例初始化块给伴生对象静态变量赋值
将配置变量传递给伴生对象的静态属性,同时给类添加@Component注解确保被Spring管理:
import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import java.time.LocalDateTime @Component class EnumUtils( @Value("\${open-date}") openDateYmd: String ) { companion object { lateinit var openDateYmd: String } // 实例初始化时赋值给伴生对象的静态变量 init { EnumUtils.openDateYmd = openDateYmd } companion object { fun getStatus(orderDate: LocalDateTime): Status { val openDateLocalDateTime = parseToLocalDateTime(openDateYmd) return when { orderDate.isBefore(openDateLocalDateTime) -> Status.VALUE_1 else -> Status.VALUE_2 // 原代码两处返回相同值,建议根据业务逻辑调整 } } // 假设parseToLocalDateTime是已实现的日期解析方法 private fun parseToLocalDateTime(dateStr: String): LocalDateTime { return LocalDateTime.parse(dateStr) // 示例解析逻辑,可根据实际格式调整 } } }
说明:Spring默认将@Component类初始化为单例,init块仅执行一次,静态变量openDateYmd只会被赋值一次,不存在线程安全问题。
方法二:移除伴生对象,改用实例方法(推荐)
遵循Spring依赖注入设计规范,将getStatus改为实例方法,直接使用注入的配置变量:
import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import java.time.LocalDateTime @Component class EnumUtils( @Value("\${open-date}") private val openDateYmd: String ) { fun getStatus(orderDate: LocalDateTime): Status { val openDateLocalDateTime = parseToLocalDateTime(openDateYmd) return when { orderDate.isBefore(openDateLocalDateTime) -> Status.VALUE_1 else -> Status.VALUE_2 } } private fun parseToLocalDateTime(dateStr: String): LocalDateTime { return LocalDateTime.parse(dateStr) // 示例解析逻辑,可根据实际格式调整 } }
使用时直接依赖注入EnumUtils实例调用方法:
@Component class SomeService(private val enumUtils: EnumUtils) { fun processOrder(orderDate: LocalDateTime) { val status = enumUtils.getStatus(orderDate) // 后续业务逻辑处理 } }
这种方式避免了静态变量的使用,更符合Spring依赖注入思想,同时更易于测试和维护。
内容的提问来源于stack exchange,提问作者rime
相关产品推荐
相关产品推荐

