Issue
I have the following code:
This is my first class that will to call the
@Component
class DefaultBridge @Autowired constructor(
private val clientConfig: Config,
private val client: world.example.Client
) : Bridge {
override fun doEpicStuff(): String {
val request = createRequest(...)
val response = client.makeCall(request)
return response.responseBody
}
}
The Client being used (world.example.Client) then has the following piece of code:
public class Client {
@Autowired
private RestTemplate restTemplate;
public Response makeCall(Request request) {
restTemplate.exchange(....)
}
}
When running the code. I get the following Error:
NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
- Where should I declare the bean when the constructor is autowired?
- why won't spring automatically create the bean?
I need help understanding the problem so please don't just post the solution.
Solution
With Spring dependency injection you can inject a instance of a bean.
In Spring it's called Inversion of Control (IoC) principle. IoC is also known as dependency injection (DI).
You can define depencenies for your bean with member variable or constuctor variables. There are differnt possibilities, for example @Autowire
as annotation for member variables like your usage.
The container then injects those dependencies when it creates your bean.
Attention, however, it is necessary that the spring container knows how the dependency to be injected. There are many ways to teach the container this. The simplest variant is to provide a @Bean
producer method in a @Configuration
class. Spring container "scans" all @Configurations
at the start of the container and "registers" the @Bean
producer.
Nobody has done a producer for RestTemplate
. Not Spring self and also no other lib. With many other beans you use, this has already been done, not with RestTemplate
. You have to provide a @Bean
producer for RestTemplate
.
Do this in a new @Configuration
or in one of your existing @Configuration
.
A @Configuration
indicates that a class declares one or more @Bean
methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
// New instance or more complex config
return new RestTemplate();
}
}
Answered By - Sma Ma
Answer Checked By - Mary Flores (JavaFixing Volunteer)