我在尝试使用Feign客户端自动装配另一个项目时遇到了问题。似乎Feign客户端的实现未被生成和注入。
这是我得到的错误信息。
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'passportRestController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.wstrater.service.contacts.client.ContactService com.wstrater.service.passport.server.controllers.PassportRestController.contactService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.wstrater.service.contacts.client.ContactService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
Feign客户端非常简单明了。出于简洁考虑,我已经删除了导入语句。
package com.wstrater.service.contacts.client;
@FeignClient("contact-service")
public interface ContactService {
@RequestMapping(method = RequestMethod.GET, value = ContactConstants.CONTACTS_USER_ID_PATH)
public Collection<Contact> contactsByUserId(@PathVariable("userId") String userId);
}
我向我的项目中添加了组件扫描,以包括应用程序和其控制器,并在另一个项目中包括feign客户端。
package com.wstrater.service.passport.server;
@EnableEurekaClient
@EnableFeignClients
@SpringCloudApplication
@ComponentScan({"com.wstrater.service.passport.server",
"com.wstrater.service.contacts.client"})
public class PassportServiceApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(PassportServiceApplication.class, args);
}
}
为了简洁起见,大部分导入模块已被删除的REST控制器。
package com.wstrater.service.passport.server.controllers;
import com.wstrater.service.contacts.client.ContactService;
@RestController
public class PassportRestController {
@Autowired
private ContactService contactService;
@RequestMapping(PassportContstants.PASSPORT_USER_ID_PATH)
public ResponseEntity<Passport> passportByUserId(@PathVariable String userId) {
ResponseEntity<Passport> ret = null;
Collection<Contact> contacts = contactService.contactsByUserId(userId);
if (contacts == null || contacts.isEmpty()) {
ret = new ResponseEntity(HttpStatus.NOT_FOUND);
} else {
ret = ResponseEntity.ok(new Passport(contacts));
}
return ret;
}
}
我曾尝试在不同的项目和不同的包中定义feign客户端接口,但只有当我将其放在应用程序相同的包中时才成功。这使我相信这是一个组件扫描问题,即使我已经将该包包含在扫描范围内。我希望将feign客户端接口保留在共享项目中以定义可重用的“契约”,并使每个项目具有独特的包结构,而不是使用应用程序定义feign客户端。
谢谢,Wes。
@EnableFeignClients(basePackages = {"com.wstrater.service.passport.server", "com.wstrater.service.contacts.client"})
。它仍然出现错误。 - Wes@SuppressWarnings("SpringJavaAutowiringInspection")
注释测试类,这将抑制这些错误警告。 - alltej