目录
一,报错信息
2020-10-16 10:58:59.622 WARN 1004 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'TController': Unsatisfied dependency expressed through field 'iFeignClientService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sgfd.service.IFeignClientService': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
2020-10-16 10:58:59.622 INFO 1004 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
二,写法
(一) service
package com.sgfd.service;
import java.util.Map;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@FeignClient(url="localhost:8088" ,value = "项目名称" )
@RequestMapping("/t")
public interface IFeignClientService {
/**
* 物联管理平台下发app镜像仓库地址及相关数据到边设备
*/
@RequestMapping("/t1")
@ResponseBody
public String t1(@RequestBody Map<String,String> map) ;
}
(二) 控制器调用
package com.controller;
import com.sgfd.feign.IFeignClientService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TControllerextends {
@Autowired
IFeignClientService iFeignClientService;
@Override
public void test(){
Map<String, String> operationMap = new HashMap<>();
operationMap.put("container", "1");//镜像名称
operationMap.put("version", "2");//镜像版本
operationMap.put("app", "3");//应用名称
operationMap.put("control", "4");// 1启动2停止3删除
iFeignClientService.t1(operationMap)
}
}
三,解决办法
一开始我以为是大众化的使用问题,注解没写完啊,启动类没加注解啊,包的问题等等。后来都没找对对应的解决办法。于是去看了下官方文档。下面这段话是关键,FeignClient注解失效了。
在使用FeignClient时,Spring会按name创建不同的ApplicationContext,通过不同的Context来隔离FeignClient的配置信息,在使用配置类时,不能把配置类放到Spring App Component scan的路径下,否则,配置类会对所有FeignClient生效.
于是把远程调用的单独分出包,EnableFeignClients注解的路径也变一下
package com.sgfd.feign;
IFeignClientService
Application
@SpringBootApplication(scanBasePackages = {"com.sgfd.service","com.sgfd.controller","com.sgfd.mode"})
@EnableFeignClients(basePackages="com.sgfd.feign")