Taking into account the following example where I'm trying to use the Sample
configuration bean within SampleStarter
to start the service with the bean properly filled. The .scala file has SampleStarter.scala
as name, with Sample
being defined within that exact same file.
@SpringBootApplication
@Service
object SampleStarter {
@(Autowired @setter)
var sample: Sample = _ // always null, @Autowired not working?
def getInstance() = this
def main(args: Array[String]): Unit = {
SpringApplication.run(classOf[Sample], args: _*)
sample.run()
}
}
@Configuration
@ConfigurationProperties("sample")
@EnableConfigurationProperties
class Sample {
@BeanProperty
var myProperty: String = _
def run(): Unit = { // bean config seems OK, when debugging with @PostConstruct the 'myProperty' value is filled properly
print(myProperty)
}
}
Whenever I hit sample.run()
after SpringApplication.run(classOf[Sample], args: _*)
, sample
property is always null. I reckon this has something to do with object
in Scala since all their members are static AFAIK. I took this SO question How to use Spring Autowired (or manually wired) in Scala object? as inspiration but still can't make my code to work.
Is there something wrong the way I'm instantiating the classes or is it something related to Scala?
EDIT
Following @Rob's answer, this is what I did trying to replicate his solution.
@SpringBootApplication
@Service
object SampleStarter {
@(Autowired @setter)
var sample: Sample = _
def getInstance() = this
def main(args: Array[String]): Unit = {
SpringApplication.run(classOf[Sample], args: _*)
sample.run()
}
}
@Configuration // declares this class a source of beans
@ConfigurationProperties("sample") // picks up from various config locations
@EnableConfigurationProperties // not certain this is necessary
class AppConfiguration {
@BeanProperty
var myProperty: String = _
@Bean
// Error -> Parameter 0 of constructor in myproject.impl.Sample required a bean of type 'java.lang.String' that could not be found.
def sample: Sample = new Sample(myProperty)
}
class Sample(@BeanProperty var myProperty: String) {
def run(): Unit = {
print(myProperty)
}
}