Home > Software design >  Could not autowire FeignClient in service
Could not autowire FeignClient in service

Time:10-15

I have a simple API who it uses a FeignClient to call on other api and get an access token. However today i don't understand why my client is null.

Can you explain why on run, my feign client is null ?

@SpringBootApplication
@EnableFeignClients
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

My Controller

@RestController
@RequestMapping("/api")
public class AppController {

    private final MyService myService = new MyService();
}

My Service

@Service
public class MyService {

    @Autowired
    private MyClient myClient;

  public AccessToken applicationLogin(final LoginParameters loginParameters) {
        return myClient.getAccessToken(loginParameters);
    }
}

My client

@FeignClient(name = "myClient", url = "https://myurl.com")
public interface MyClient {

    @PostMapping("/auth/login")
    AccessToken getAccessToken(@RequestBody LoginParameters loginParameters);
}

Error

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException: null

CodePudding user response:

You are using wrong variable to invoke the method instead of r2aClient you should ise myClient

public AccessToken applicationLogin(final LoginParameters loginParameters) {
    return myClient.getAccessToken(loginParameters);
}

Edit based in new changes

I guess the @EnableFeignClient is not able to find the class MyClient, try @EnableFeignClient(basePackages = "<your package for MyClient>)

CodePudding user response:

I think you have to inject the Service in your Controller. You created your Service as a normal Java-class so the MyClient is not injected.

@RestController
@RequestMapping("/api")
public class AppController {
    @Autowired
    private final MyService myService;
}
  • Related