In spring boot 3, how do I define a custom configu...
# spring
c
In spring boot 3, how do I define a custom configuration that is also @Component annotated? When I define a data class with the configurarion properties;
Copy code
@Component
@ConfigurationProperties("testconfig")
data class TestConfiguration(var eyes: String, var nose: String)
I can see the property in the
application.properties
file but, in the repository where I want to use this component, I see an error
"could not autowire"
, and when I run the app it crashes because it couldn’t find
TestConfiguration
, how do I fix this please?
c
in one of your @Configuration classes use
@EnableConfigurationPropertis
referencing this class.
c
You mean in the main application
@SpringBootApplication
annotated class?
c
sure, there or any other @Configuration class that you use.
c
I do have another
@ConfigurationProperties
annotated class, and used it with
@EnableConfigurationProperties
and that one works, I’m new to spring so I’m trying to do the same thing using the
@Component
on the class, this doesn’t use the enable approach so I expected it to work without needing to use that other approach
c
it will only work with the combination of
@EnableConfigurationProperties
(which register the class for properties binding) and
@ConfigurationProperties
(which specifies the binding prefix).
imo, while binding configuration properties is very powerful, the annotation-based approach is clunky and confusing.
c
I feel so, I think I get lost by the many annotations, and for this specifically I think these are different ways of achieving the same thing but using the annotations differently, kinda confusing. I’m trying to learn using the Spring boot 3.0 book which is java based
c
I’ve moved away from annotations for recent Kotlin/Spring projects in favour of functional bean registration. It vastly simplifies the code, makes it clear what it going on (no annotation magic to decipher). For example, this is a configuration properties bean (it uses some custom extensions as SB doesn’t yet fully support functional bean registration):
Copy code
public fun frontEndModuleBeans(): BeanDefinitionDsl = beans {
    configurationPropertiesBean<FrontEndProperties>(prefix = "frontend")
}
c
That’s nice! Haven’t gotten to this level yet haha, I love when things are done in a Kotlinesque way, aside from the official docs, sadly there are not many resources for Spring Boot 3 with Kotlin like Greg’s book.
c
yea. while Spring does have solid Kotlin support it takes a bunch of research etc to figure it all out.
👍 1
c
Do you have any resources can you recommend?
c
Yeah, even the docs weren’t so helpful to just find small details that should be straightforward, you’ll almost need to go through a very long reading each time
c
it helps to find sample applications where possible. docs are ok, but often don’t show how everything goes together.
💚 1
918 Views