Home > Software design >  Can we use restTemplate in service classes instead of controller classes in spring boot? Please prov
Can we use restTemplate in service classes instead of controller classes in spring boot? Please prov

Time:11-11

Do we need to include any notations if we use restTemplate inside service classes?

CodePudding user response:

Why wouldn't you? Just declare it as a dependency:

@Service
public class WhateverService {
    @Autowired
    private RestTemplate restTemplate;

    (...)
}

Or using constructor injection:

@Service
public class WhateverService {
    private RestTemplate restTemplate;

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

    (...)
}

CodePudding user response:

You can either @Autowired the RestTemplate class or you can create a bean of it.

  • Related