考虑到下面的示例,我尝试在SampleStarter中使用SampleStarter配置bean来使用正确填充的bean启动服务。.scala文件以SampleStarter.scala作为名称,在该文件中定义了Sample。
@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)
}
}每当我在sample.run()之后点击SpringApplication.run(classOf[Sample], args: _*),sample属性总是为null。我认为这与Scala中的object有关,因为它们的所有成员都是静态的。我把这个问题看作是对How to use Spring Autowired (or manually wired) in Scala object?的启发,但仍然无法使我的代码工作。
我实例化类的方式有问题吗?还是与Scala有关?
编辑
按照@Rob的回答,这就是我试图复制他的解决方案的方法。
@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)
}
}发布于 2020-10-15 11:55:07
@Configuration声明了一个能够提供@Bean的源文件,这不是您想要的。您希望/需要将示例作为POJO类(POSO?)然后让另一个类"AppConfiguration“(比方说)加上@Configuration注释,以创建一个类型为Sample的@Bean
我的scala非常生疏,所以这可能根本不编译,但是结构应该大致正确。
@Configuration // declares this class a source of beans
@ConfigurationProperties("sample") // picks up from various config locations
@EnableConfigurationProperties // not certain this is necessary
class AppConfiguration {
@Bean
def getSample(@BeanProperty myProperty: String): Sample = new Sample(myProperty)
}class Sample {
var myProperty: String
def Sample(property : String) = {
this.myProperty = myProperty
}
def run(): Unit = {
print(myProperty)
}
}现在您有了一个Sample类作为@Bean,它可以在任何需要的地方都是@Autowired。
@SpringBootApplication
@Service
object SampleStarter {
// note its typically better to inject variables into a constructor
// rather than directly into fields as the behaviour is more predictable
@Autowired
var sample: Sample
def getInstance() = this // not required ??
def main(args: Array[String]): Unit = {
SpringApplication.run(classOf[Sample], args: _*)
sample.run()
}
}FWIW,您可以独立启动SpringBoot应用程序,并具有完全独立的@Service逻辑。@Service是另一种类型的@Bean,可供SpringBootApplication的其他部分使用。
https://stackoverflow.com/questions/64370817
复制相似问题