I have the following spring pseudo-code wired scala class.
@Service
class Something {
@Value("${some.property}")
val someString : String
// do something with someString in the body
}
However this won’t work because the someString is part of the constructor body, and spring can’t wire in the values until after the constructor has executed.
How can I wire in @Value’s so that it works, and isn’t horrible (my current solution with a custom constructor containing all the values I need just doesn’t feel “scala” and looks horrible.
Edit: To clarify, my current solution is this:
@Service
class Something {
@Autowired
def this(@Value("${some.prop}") prop : String) {
this()
// do other construction stuff here
}
}
I just think it looks ugly and feel there is a better way. I also don’t like having to create these secondary constructors when I’d rather enforce it on the primary constructor.
Edit 2: To further clarify, I was hoping there was a way to do something like this:
@Service
class Something(@Value("${some.property}") string : String) {
// use the value in your constructor here
}
Because this looks far more elegant. I just can’t get it to work 🙂
Ok, after all the back and forth, I think I understand better what you want, so here’s my take on it:
This is essentially Paolo Falabella’s solution, except that I try to avoid having Spring acces private fields. To this end I let scala autogenerate a public java-like setter using
@BeanPropertyand apply@Valueon it.You can also improve the syntax somewhat by using a type alias: