我已经认真地调试了这个用Scala编写的与Spring相关的问题一个多星期了,我非常渴望寻求外部帮助。基本上,我的应用程序在Spring的基础上具有一些功能,可以在一个回购中工作,但由于代码迁移的严格限制,我需要将这些代码移动到一个新的回购中
大多数时候,我在新的回购中分离了Spring应用程序的基础知识,遵循这个基于通用模块的Gradle项目结构
da-report
|src
|main
|java
com.abc.da.app
service/
ComService
AppConfig
ComApp
|resources
build.gradle
然而,由于一个非常奇怪的原因,我一直让服务类没有在主应用程序类中被扫描/自动连接(这太不可思议了,我不明白为什么它不应该工作)。
Field service in com.abc.da.app.service.ComApp required a bean of type 'com.abc.da.app.service.ComService' that could not be found.
Action:
Consider defining a bean of type 'com.abc.da.app.service.ComService' in your configuration.
PS:如果我只显示代码的关键部分(忽略导入语句和YAML文件中的其他配置),请提前道歉
我已经*检查了所有必要的注释或基于工作版本的逻辑*(在以前的repo中)-换句话说,这些注释看起来足以自动布线(但奇怪的是,它们没有连接)
我曾尝试将服务子包的位置更改为与主应用程序包目录相同的级别,但不起作用。
ComService
....
@Service
class ComService [
}
ComApp
...
object ComApp extends App {
val cxt = new SpringApplicationBuilder().sources(classOf[ComApp])).run(args: _*)
println("contain service class? " + cxt.getBean(""))
}
@SpringBootApplication
@Import(Array=(classOf[AppConfig]))
@EnableAutoConfiguration()
class ComApp extends ApplicationRunner {
@Autowired var service: ComService = _
override def run(applicationArguments: applicationArgument) ={
}
}
AppConfig
....
@Configuration
@ComponentScan(basePackages = Array("com.abc.da.app.service"))
class AppConfig {
}
如前所述,逻辑被完全忽略,只是为了测试服务类是否被识别。我真的希望服务子包下的任何类都能被扫描(甚至不需要包括@ComponentScan,因为应用程序类已经位于根包中)
所以,我撞到头了,但不知道是什么原因导致了这个最奇怪的bug。可能是因为包命名?它的命名逻辑有什么限制吗;导致错误的文件结构?
或者,我会犯任何与Spring语义相关的愚蠢、代价高昂的错误吗?
我在Scala 2.12.8&JDK 1.8。其工作
//ComApp.scala
object ComApp extends App {
val cxt = new SpringApplicationBuilder().sources(classOf[ComApp]).run(args: _*)
println("contain service class? " + cxt.getBean("comService"))
}
@SpringBootApplication
@Import(value = Array(classOf[AppConfig]))
@EnableAutoConfiguration()
class ComApp extends ApplicationRunner {
@Autowired var service: ComService = _
override def run(applicationArguments: ApplicationArguments) ={
service.demo("hello")
}
}
//ComService.scala
@Service
class ComService {
def demo(str: String): Unit = println(str)
}
//AppConfig.scala
@Configuration
@ComponentScan(basePackages = Array("com.abc.da.app.service"))
class AppConfig
我在你的代码中发现了一些问题
例如,导入注释应具有值=数组而非数组=
Import(value = Array(classOf[AppConfig]))
cxt.getBean(""))
这将给出错误,因为Bean名称为空
希望这能帮助