我有一个utils类,它以静态方法从外部API获取数据:
@Component
public class Util {
private Util() {
}
public static List<Movie> getMovies(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
String resourceURL = "< a loooong url>"
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Results> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity, Results.class);
Results results = response.getBody();
List<Movie> movies = results.getResults();
return movies;
}
}
我知道数据已从服务器中正确提取,但我不知道为什么我无法将数据传输到我的其他控制器:
@RestController
public class MovieController {
@RequestMapping(value ="/movies", method = RequestMethod.GET)
public List<Movie> getMovies(){
return Util.getMovies();
}
}
它返回给我404没有可用的消息..
任何想法的家伙? ;)
问候
答案 0 :(得分:1)
你有必要让方法静态吗?将其切换为非静态方法,然后您可以在控制器中自动装配它。
@Component
public class Util {
public List<Movie> getMovies(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
String resourceURL = "< a loooong url>"
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Results> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity, Results.class);
Results results = response.getBody();
List<Movie> movies = results.getResults();
return movies;
}
}
由于它是一个组件,您现在可以自动装配它,您还必须将@ResponseBody
注释添加到控制器。
@RestController
public class MovieController {
@Autowired
private Util util;
@RequestMapping(value ="/movies", method = RequestMethod.GET)
public @ResponseBody List<Movie> getMovies(){
return util.getMovies();
}
}