从静态类接收数据

问题描述 投票:0回答:1

我有一个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没有可用的消息..

有什么想法吗? ;)

问候

java spring rest api http
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.