Springboot @ConfigurationProperties

Kotlin

properties class

1
2
3
4
5
6
@Component
@ConfigurationProperties("foo")
class AppProperties {
lateinit var a: String
lateinit var b: String
}
1
2
@EnableConfigurationProperties(AppProperties::class)
class Application

pom.xml

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

Example

单层属性

application-dev.properties

1
2
foo.a=a
foo.b=b
1
2
3
4
5
@Autowired
lateinit var appProperties: AppProperties

print(appProperties.a)
print(appProperties.b)

嵌套多层

1
2
3
4
5
6
7
8
9
@Component
@ConfigurationProperties("custom")
class AppProperties {
var filter: Filter? = null

class Filter {
var exclude: String = ""
}
}

单元测试出现的问题

在单元测试中无法初始化AppProperties,原因如下:

MockMvc doesn’t use the main class, so EnableConfigurationPropertiesis not processed. MockMvc or WebMvcTest
is designed to test the web layer (duh!), not the whole app. Using either of those. the properties bean should
be set by the test.