如何使用Scala将ConfigurationProperties注入s Configuration类

时间:2018-01-18 09:53:52

标签: java spring scala spring-boot

使用Scala编写spring-boot应用程序时,我遇到了如何将ConfigurationProperties注入s Configuration类的问题。

我尝试了以下代码:

@Configuration
class Config @Autowired() (var properties: MessagePathProperties)

但发生了异常:

Caused by: java.lang.NoSuchMethodException: configuration.Config$$EnhancerBySpringCGLIB$$c8875845.<init>()

我也试过像:

这样的代码
@Configuration
class Config {
     @Autowired private var properties: MessagePathProperties = _
    ...
}

应用程序本身正常启动,但我发现properties在配置中为空。

与此同时,我尝试在服务类中注入属性,如:

@Service
class MessageService @Autowired() (var properties: MessagePathProperties)

并且properties在MessageService类中正常工作。

所以,我不知道@Configuration和@Service之间的区别是什么产生了不同的效果。

BTW,这是我的app类作为参考:

@SpringBootApplication
@EnableAutoConfiguration
@EnableConfigurationProperties
class ScalaServiceApplication

object Launch extends App {
  SpringApplication.run(classOf[ScalaServiceApplication], args :_ *)
}

2 个答案:

答案 0 :(得分:0)

建议您使用spring的隐含参数insead。

建议您使用implicits insead 假设您需要将记录器注入到worker中,并且可能存在不同类型的记录器:

case class Worker(in: String)(implicit logger: Logger) {
  def work(): Unit = {
    logger.log(s"working on $in")
    // doing some work here
  }
}

trait Logger {
  def log(message: String)
}

case class ConsoleLogger() extends Logger {
  override def log(message: String): Unit = {
    // just prints the message
    println(message)
  }
}

object MyApp extends App {
  implicit val logger: Logger = ConsoleLogger()
  // logger in current scope (ConsoleLogger) would be injected into worker
  val worker = Worker("some work")
  worker.work()
}

答案 1 :(得分:0)

我找到了案件的原因以及如何解决它。

实际上,我还在PropertySourcesPlaceholderConfigurer课程中创建了一个Config bean,但是在控制台上有一个变暖的消息,

@Bean method Config.propertySourcesPlaceholderConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.

所以,我只是将方法移动到scala对象中,如:

object Config {
  @Bean def propertySourcesPlaceholderConfigurer: PropertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer
}

因此,一切正常。