One of the methods to handle the value of the configuration file in the application in Spring Boot.
application.yaml
sample:
hoge: hogeValue
huga: hugaValue
piyo: piyoValue
When there is a setting value such as
package com.wakye.property
import ........
@ConstructorBinding
@ConfigurationProperties("sample")
data class SampleProperty(
val hoge: String,
val huga: String,
val piyo: String
)
By adding the ConfigurationProperties annotation to the class that has the field corresponding to the setting value in this way, the value is bound and then registered as a bean.
The ConstructorBinding annotation has nothing to do with the main line, but if you are developing a SpringBoot application with kotlin, it is used to add the ConfigurationProperties annotation to the data class.
Now, the problem is when getting this bean.
Normally, there is no problem in getting the function of Spring Boot to be injected as a constructor.
However, I had to get the registered bean by specifying the bean name, but there was a problem. By using the getBean method defined in ApplicationContext, it is possible to get the registered bean from the bean name.
In Spring Boot, the bean name defaults to the lower camel case of the class name. (The class name is defined only in the upper camel case, so maybe the battle is just in lowercase)
So
applicationContext.getBean("sampleProperty")
Exception occurred even if I tried to get it like this, it seems that the bean defined as sampleProperty does not exist.
A few hours to google. .. .. .. .. .. ..
Find those descriptions in the documentation! !! !!
When the @ConfigurationProperties bean is registered that way, the bean has the traditional name \
-\ . is the environment key prefix specified in the @ConfigurationProperties annotation and is the fully qualified name of the bean. If the annotation does not provide a prefix, only the bean's fully qualified name is used.
[Official document quote](https://spring.pleiades.io/spring-boot/docs/2.1.3.RELEASE/reference/html/boot-features-external-config.html#boot-features-external-config- typesafe-configuration-properties)
Apparently it doesn't register with a normal bean name.
In this case
prefix is sample
fqn is com.wakye.property
So the bean name is
sample-com.wakye.property.SampleProperty
It seems to be.
applicationContext.getBean("sample-com.wakye.property.SampleProperty")
Successful acquisition here.
It was a pitfall that was difficult to understand.
Recommended Posts