首页 > 解决方案 > 无法在服务中自动装配 FeignClient

问题描述

我有一个简单的 API,它使用 FeignClient 调用其他 api 并获取访问令牌。但是今天我不明白为什么我的客户是空的。

你能解释为什么在运行时,我的假客户是 null 吗?

@SpringBootApplication
@EnableFeignClients
public class App {

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

我的控制器

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

    private final MyService myService = new MyService();
}

我的服务

@Service
public class MyService {

    @Autowired
    private MyClient myClient;

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

我的客户

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

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

错误

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

标签: javaspringspring-bootspring-cloud-feign

解决方案


我认为你必须Service在你的Controller. 您将 Service 创建为普通的 Java 类,因此MyClient不会注入。

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

推荐阅读