-1

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
A.Rouze
  • 51
  • 1
  • 10

3 Answers3

1

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>)

Ravik
  • 694
  • 7
  • 12
1

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;
}
UKoehler
  • 131
  • 7
0

do not use

new MyService();

if use 'new',it will not be managed by spring. you could check it by

@RestController
public class MyController {
    
    private IMyService iMyService = new MyServiceImpl();
}
@Service
public class MyServiceImpl implements IMyService {

   @Autowired
   private MyMapper myMapper;

  //....

}

myMapper will always be null.cuz you create it by new. by the way,since Spring 4,field injection is not recommended

GarraWong
  • 1
  • 1