当我在我的服务中注入feignClient接口时出现错误。这是我使用的 Spring 启动和 Spring 云版本:
org.springframework.boot:spring-boot-starter-parent:2.0.6.RELEASE 春云版:芬奇利.SR2
但是当我在我的类服务中创建假客户端 bean 时,它可以工作。
创建客户假客户端:
@Component("DepartmentClient")
@FeignClient(name = "DEPARTMENT-SERVICE", url = "http://test")
public interface DepartmentClient {
@RequestMapping(value = "/department/{departmentId}", method = RequestMethod.GET)
void findDepartmetById(@PathVariable("departmentId") int departmentId);
}
我在服务中注入这个假客户端,例如
@Service
public class AgentService {
Logger logger = LoggerFactory.getLogger(AgentService.class);
@Autowired
private AgentRepository agentRepository;
@Autowired
private DepartmentClient departmentClient;
....
}
输出
Field departmentClient in ...AgentService required a bean of type '...DepartmentClient' that could not be found.
The injection point has the following annotations:
org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type .... DepartmentClient' in your configuration.
要使假客户端正常工作,您必须将@EnableFeignClients
添加到Configuration class
或@SpringBootApplication class
@SpringBootApplication
@EnableFeignClients
public class FooMain { // Your Main class
public static void main(String[] args) {
SpringApplication.run(FooMain.class, args);
}
}
我有一个类似的例外,但是我的@SpringBootApplication
课上已经有@EnableFeignClients
了。 尽管如此,Spring 还是无法从 FeignClient 界面创建 clientBean。
事实证明,我必须为注释提供basePackages值。如果没有它,Spring 不会从 @FeignClient
接口创建 LoadBalanced HTTP 客户端类。
@EnableFeignClients(basePackages = "com.xxx.xxx")
也许是因为我总是将我的应用程序类保存在配置包中,而其他代码与该包并行。
您是否尝试过删除假装界面的@Component?
否则看你的弹簧应用程序组件扫描,如果你的接口没有扫描 bean 将不会创建
在下面的答案中添加更多详细信息:
在@FeignClient批注中,字符串值(上面的"部门"(是任意客户端名称,用于创建功能区负载均衡器。您还可以使用 url 属性(绝对值或仅主机名(指定 URL。应用程序上下文中 Bean 的名称是接口的完全限定名称。要指定您自己的别名值,您可以使用@FeignClient注释的限定符值。
为了使 Feign 客户端正常工作,以下是我们需要执行的步骤:
1. Feign 客户端的变化:它应该是一个带有 Feign 客户端注释的界面
@FeignClient(
name = "DEPARTMENT-SERVICE",
configuration = {DepartmentConfiguration.class},
fallback = DepartmentFallback.class
)
@RequestMapping(
value = {"${service.apipath.department}"},
consumes = {"application/json"},
produces = {"application/json"}
)
public interface DepartmentClient {
@RequestMapping(value = "/department/{departmentId}", method =
RequestMethod.GET)
void findDepartmetById(@PathVariable("departmentId") int departmentId);
}
2. 主类的变化:
@EnableFeignClients
@SpringBootApplication
public class DepartmentApplication {
public static void main(String[] args) {
SpringApplication.run(DepartmentApplication.class, args);
}
}