【问题标题】:How to inject a ConfigurationProperties to s Configuration class with Scala如何使用 Scala 将 ConfigurationProperties 注入到配置类
【发布时间】:2018-01-18 09:53:52
【问题描述】:

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

我试过这样的代码:

@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在Config中为null。

同时,我尝试将属性注入到服务类中,例如:

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

properties 在 MessageService 类中正常工作。

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

顺便说一句,这是我的应用类作为参考:

@SpringBootApplication
@EnableAutoConfiguration
@EnableConfigurationProperties
class ScalaServiceApplication

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

【问题讨论】:

  • 将spring放入垃圾袋,使用scalaimplicits insead
  • 谢谢你的回复,伊戈尔。但是请您提供一些代码吗?我是 scala 的新生...
  • 首先阅读 Martin Odersky,Lex Spoon Programming Scala,关于隐含。 scala 语言的这一特性难以理解,但非常强大,并且可以直接替换所有“DI”框架,无需任何注释。 2.示例

标签: java spring scala spring-boot


【解决方案1】:

推荐你在spring中使用隐式参数。

建议你使用implicits insead 假设您需要将 logger 注入到 worker 中,并且可能有不同种类的 logger:

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()
}

【讨论】:

    【解决方案2】:

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

    其实我也在Config类中创建了一个PropertySourcesPlaceholderConfigurer 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
    }
    

    因此,一切正常。

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2020-08-05
      • 2015-09-12
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2017-01-18
      • 2017-08-07
      • 2017-02-14
      相关资源
      最近更新 更多