Spring Boot Demo 测试的 Controller 类代码如下:
import com.sztxtech.springcloud.microservicesimpleprovideruser.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findUserById(@PathVariable Long id){
return this.restTemplate.getForObject("http://localhost:7900/simple/"+id, User.class);
}
}
其中如下图示代码编译报错:
检查代码、导包都没问题 。在网上找到一个解决办法说是要修改 IDE settings 设置:
按照此法修改设置后,编译通过,但是在启动时报错:
完整错误信息如下:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field restTemplate in com.sztxtech.springcloud.microservicesimplecustomermovie.controller.MovieController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
Process finished with exit code 1
之后在https://www.cnblogs.com/EasonJim/p/7546136.html找到完美的解决办法,并有出现此问题的原因。
解决办法,出现此问题的原因是因为RestTemplate
没有定义,也就是该对象没有实例化,找不到这个 bean ;此时可能会有两种错误提示:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
或者
No qualifying bean of type [org.springframework.web.client.RestTemplate] found
所以就需要对 RestTemplate 进行定义,但是对不同版本的Spring,以及不同版本的 Spring Boot 会有不同的处理方式;这里按照教程指导,使用的是 Spring Boot 1.4.1,所以采用以下处理办法,至于其他版本的问题,可查看以上源链接详解。
import com.sztxtech.springcloud.microservicesimpleprovideruser.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class MovieController {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findUserById(@PathVariable Long id){
return this.restTemplate.getForObject("http://localhost:7900/simple/"+id, User.class);
}
}
添加对 RestTemplate的定义,并将之前对 IDE settings 的修改还原之后,编译通过、启动正常,问题解决。
以上添加的代码实际上就相当于:private RestTemplate restTemplate = new RestTemplate();
最终浏览器的访问结果如下: