我创建了一个多模块Maven项目,其中包含library
模块(Spring Boot入门应用程序)和application
模块(已经包含library
作为依赖项的Spring Boot应用程序)。 / p>
这是我的项目的结构:
.
├── application
│ ├── pom.xml
│ └── src
│ ├── main
│ │ ├── kotlin
│ │ │ └── com
│ │ │ └── application
│ │ │ ├── ApplicationService.kt
│ │ │ └── Application.kt
│ │ └── resources
│ │ └── application.properties
│ └── test
│ └── kotlin
│ └── com
│ └── application
│ └── ApplicationServiceTest.kt
├── library
│ ├── pom.xml
│ └── src
│ └── main
│ ├── kotlin
│ │ └── com
│ │ └── application
│ │ ├── LibraryService.kt
│ │ └── Properties.kt
│ └── resources
│ ├── META-INF
│ │ └── spring.factories
│ └── config
│ └── application.properties
└── pom.xml
图书馆/.../ Properties.kt:
@ConfigurationProperties("properties")
class Properties {
lateinit var name: String
}
library /.../ LibraryService.kt:
@Service
@EnableConfigurationProperties(Properties::class)
class LibraryService(private val properties: Properties) {
fun name() = properties.name
}
图书馆/.../ spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.application.LibraryService
库/.../ config / application.properties:
properties.name=library
应用程序/.../ Application.kt
@SpringBootApplication
class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
应用程序/.../ ApplicationService.kt
@Service
class ApplicationService(private val libraryService: LibraryService) {
fun call() = libraryService.name()
}
应用程序/.../ application.properties
properties.name=application
因此,我有一个library
模块,在其中放置了带有默认参数application.properties
的{{1}}文件。 properties.name=library
模块在library
中注入了Property
类。 LibraryService
具有简单的方法LibraryService
,该方法仅从属性返回值。我也有name()
模块,在application
中使用LibraryService
并调用ApplicationService
函数,但是在name()
模块中有application.properties
,其中{{ 1}}。
我希望application
properties.name=application
会覆盖application's
properties.name=application
,而library's
必须返回值properties.name=library
而不是默认值ApplicationService::call
在application
中的library
中。但这不会发生。 properties.name
返回值library module
。
我创建了简单的junit测试来重现此行为( ApplicationServiceTest.kt ):
ApplicationService::call
它打印library
。我希望具有以下行为:@SpringBootTest
class ApplicationServiceTest {
@Autowired
lateinit var applicationService: ApplicationService
@Test
fun test() {
println(applicationService.call())
}
}
具有一些已定义的默认属性,但是我希望能够覆盖library
中的其中一些属性。如何实现?
源代码:https://github.com/grolegor/maven-multi-module-spring-starter
答案 0 :(得分:1)
4.2.3。应用程序属性文件 SpringApplication从位于以下位置的application.properties文件加载属性,并将其添加到Spring Environment:
1 。当前目录的/ config子目录
2 。当前目录
3 。类路径/ config包
4 。类路径根
列表按优先级排序(在列表中较高位置定义的属性会覆盖在较低位置定义的属性)。
因此,在您的情况下,将使用[library] config/application.properties
,因为它比[application] application.properties
高。
此外,您不能两次使用application.properties
。
在存储库中查找,建议您从库模块中删除/config/application.properties
,并在Properties
类中提供默认值
package com.application
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("properties")
class Properties {
var name: String = "library"
}