Search code examples
micronaut

how to define Bean to `RestTemplate`?


I am trying to use RestTemplate from Spring-client.

I cannot use RestTemplate because this class hasnot bean.

 public BusinessBankingTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

i tried to find some documentation, for example from this https://docs.micronaut.io/latest/guide/index.html#factories

but i still have no idea how to implement it on Java language

This is my error log.

Message: No bean of type [org.springframework.web.client.RestTemplate] exists. Ensure the class is declared a bean and if you are using Java or Kotlin make sure you have enabled annotation processing.
Path Taken: new TransactionCheckerJob(BcaService bcaService,Oauth2Template oauth2Template,[BusinessBankingTemplate businessBankingTemplate]) --> new BusinessBankingTemplate([RestTemplate restTemplate])
        at io.micronaut.context.AbstractBeanDefinition.getBeanForConstructorArgument(AbstractBeanDefinition.java:981)
        at bank.transaction.service.impl.$BusinessBankingTemplateDefinition.build(Unknown Source)
        at io.micronaut.context.DefaultBeanContext.doCreateBean(DefaultBeanContext.java:1331)
        at io.micronaut.context.DefaultBeanContext.createAndRegisterSingleton(DefaultBeanContext.java:1914)
        at io.micronaut.context.DefaultBeanContext.getBeanForDefinition(DefaultBeanContext.java:1635)

Solution

  • After try to find some documentation, i found from micronaut user's guide has a feature where to register other class to bean like this.

    @Factory
    public class RestTemplateFactory {
    
        @Bean
        @Singleton
        public RestTemplate v8Engine() {
          return new RestTemplate();
        }
    }
    

    this code run well :)