我有以下 spring 伪代码有线 scala 类。
@Service
class Something {
@Value("${some.property}")
val someString : String
// do something with someString in the body
}
但是这不起作用,因为 someString 是构造函数主体的一部分,并且 spring 在构造函数执行之前无法连接这些值。
我怎样才能连接@Value's,以便它可以工作,并且不可怕(我当前的解决方案具有包含我需要的所有值的自定义构造函数,只是感觉不“scala”并且看起来很糟糕。
编辑:澄清一下,我当前的解决方案是这样的:
@Service
class Something {
@Autowired
def this(@Value("${some.prop}") prop : String) {
this()
// do other construction stuff here
}
}
我只是觉得它看起来很丑,并且觉得有更好的方法。当我宁愿在主构造函数上强制执行这些辅助构造函数时,我也不喜欢必须创建这些辅助构造函数。
编辑2:为了进一步澄清,我希望有一种方法可以做这样的事情:
@Service
class Something(@Value("${some.property}") string : String) {
// use the value in your constructor here
}
因为这看起来更加优雅。我就是无法让它工作:)
最佳答案
好吧,经过反复讨论,我认为我更好地理解了你想要什么,所以这是我的看法:
import scala.annotation.BeanProperty
import scala.annotation.target.beanSetter
class Something @Autowired() (@(Value @beanSetter)("{some.property}") @BeanProperty var prop: String)
这本质上是 Paolo Falabella 的解决方案,只是我尝试避免 Spring 访问私有(private)字段。为此,我让 scala 自动生成一个公共(public)的类似 java 的 setter,使用 @BeanProperty
并在其上应用 @Value
。
您还可以通过使用类型别名来稍微改进语法:
type Value = org.springframework.beans.factory.annotation.Value @beanSetter @beanGetter
class Something @Autowired() ( @BeanProperty@Value("{some.property}") var prop: String)
关于spring - 构造函数体中的 Scala Spring @Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123714/