SpringBoot项目Service中注入FeignClient为null是什么原因?
FeignClient实例为Null的根因
核心问题出在AppController中手动实例化MyService的逻辑:你直接通过new MyService()创建的对象不受Spring容器管理,因此MyService内部通过@Autowired声明的MyClient不会被Spring自动注入赋值,最终调用时就会触发空指针异常。
修复方案
- 第一步:修改
AppController中MyService的实例化方式,改为Spring注入,不要手动new:
@RestController @RequestMapping("/api") public class AppController { // 方式1:@Autowired注入 @Autowired private MyService myService; // 方式2:构造器注入(更推荐,Spring 4.3+无需额外加@Autowired注解) // private final MyService myService; // public AppController(MyService myService) { // this.myService = myService; // } }
- 第二步(可选优化):将
MyService中的MyClient也改为构造器注入,提前发现注入异常,避免运行时空指针:
@Service public class MyService { private final MyClient myClient; public MyService(MyClient myClient) { this.myClient = myClient; } public AccessToken applicationLogin(final LoginParameters loginParameters) { return myClient.getAccessToken(loginParameters); } }
- 第三步(兜底校验):如果你的
MyClient接口和启动类App不在同一个包路径下,需要在@EnableFeignClients注解中指定扫描路径,确保Feign接口被Spring正确识别:
// 示例:指定Feign接口所在的包路径 @SpringBootApplication @EnableFeignClients(basePackages = "com.your.project.feign") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
内容的提问来源于stack exchange,提问作者A.Rouze
相关产品推荐
相关产品推荐

