SpringCloud feign无法注入接口

接口:

package cn.mn.app.service;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name="sc-provider")
public interface IGoodsClient {
	@RequestMapping(value = "/goods/query",method = RequestMethod.GET)
	String query();
}

controller

package cn.mn.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.mn.app.service.IGoodsClient;

@RestController
@RequestMapping("/goods")
public class GoodsController {
	@Autowired
	private IGoodsClient goodsClient;
	@GetMapping("/q")
	public String query(){
		return goodsClient.query();
	}
}

这里把接口直接注入。

启动类:

package cn.mn.app.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(scanBasePackages = { "cn.mn.app.controller" })
@EnableDiscoveryClient
@EnableFeignClients
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
        
    }
    
//    @LoadBalanced
//    @Bean
//    RestTemplate restTemplate(){
//    	return new RestTemplate();
//    }
}

启动报错,无法注入IGoodsClient。

原因是没有使用@EnableFeignClients扫描指定包。修改启动类

package cn.mn.app.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(scanBasePackages = { "cn.mn.app.controller" })
@EnableDiscoveryClient
@EnableFeignClients("cn.mn.app.service")
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
        
    }
    
//    @LoadBalanced
//    @Bean
//    RestTemplate restTemplate(){
//    	return new RestTemplate();
//    }
}

正常。

你可能感兴趣的:(springcloud)