Aurelman
Aurelman

Reputation: 63

Kotlin Spring could not autowired an @Bean annoted

I'm encountering an issue with spring and kotlin :

Here it is :

I have a class MyConfig defined as such

@Configuration
class MyConfig

   @Bean
   fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
        builder.build()

On the other side I have an other class MyService defined as such

@Component
class MyService constructor(private val restTemplate: RestTemplate) {

    fun test() {
        // Use restTemplate
    }
}

But all I get is the following message :

Description:

Field restTemplate in my.package.MyService required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

This issue only occurs with beans defined in @Configuration class (annotated with @Bean) but not with bean declared as @Component or @Service.

I have no such issue with the same kind of architecture in pure-Java.

So, have I missed something?

Upvotes: 3

Views: 10073

Answers (1)

zsmb13
zsmb13

Reputation: 89578

Your restTemplate method isn't inside your MyConfig class - you've declared an empty class followed by a top level function. You're missing the curly braces that make the function a method inside the class:

@Configuration
class MyConfig {

   @Bean
   fun restTemplate(builder: RestTemplateBuilder): RestTemplate =
        builder.build()

}

Upvotes: 11

Related Questions