Skip to content
Advertisement

How to call class from another module in SpringBoot, Java

I have a Spring Boot multi-module gradle project, and I am trying to call class from another module. I have a HttpDataClient.java class that I would like to call in DataResolver.java class in another module.

HttpDataClient.java

public class HttpDataClient implements DataClient{

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpDataClient.class);

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public HttpDataClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public DataResponse getData(String dataId) {
        try{
            JsonNode node = restTemplate.exchange(
                    String.format("/data/%s", dataId),
                    HttpMethod.POST,
                    new HttpEntity<>(buildRequest(dataId), headers()),
                    JsonNode.class
            ).getBody();
            return dataResponse(node);
        }catch (HttpStatusCodeException e) {
            String msg = String.format(
                    "Error getting data for dataId: %s",
                    dataId,
                    e.getStatusCode(),
                    e.getResponseBodyAsString());
            LOGGER.error(msg);
            return dataResponse.failed();
        }
    }

    private MultiValueMap<String, String> headers() {
        final LinkedMultiValueMap<String, String> mv = new LinkedMultiValueMap<>();
        mv.set(HttpHeaders.CONTENT_TYPE, "application/json");
        return mv;
    }

    private DataResponse dataResponse(JsonNode node) {
        return DataResponse.dataResponse(
                asString(node, "dataId"),
                asString(node, "dataAuthor"),
                asString(node, "dataAuthorId")
        );
    }

    private JsonNode buildRequest(String dataId) {
        ObjectNode root = objectMapper.createObjectNode();
        root.put("dataId", dataId);
        return root;
    }
} 

So, this class should return some response data from Data service. After I would like to get that response data and do something in class in other module.

I am trying to do it like this:

DataResolver.java

public class DataResolver {

    private final HttpDataClient client;

    public DataResolver(HttpDataClient client) {
        this.client = client;
    }
}

But my HttpGameDataClient class that I am trying to use it is not recognized by DataResolver.java class.

What am I missing here? Any advice is appreciated.

Advertisement

Answer

Be sure the module you need is put as a dependency to the module who need it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement