我正在運行一個簡單的 Spring 啟動應用程式,它從 MySQL 資料庫中檢索國家/地區的詳細資訊。我在運行應用程式時得到的初始回應是 json。但是,在application.properties檔案中進行一些編輯后,我現在可以在 XML 中獲得回應。有什么辦法可以恢復到 json 回應?此應用程式是我嘗試使用 Spring 云網關和 Eureka 服務器構建的微服務應用程式的一部分。
應用程式屬性
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url= jdbc:mysql://localhost:3306/countries-microservice
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.application.name=countries-service
server.port=3001
eureka.client.serviceUrl.defaultZone=http://localhost:3000/eureka/
CountryRepository.java
package com.example.countriesservice.repository;
import com.example.countriesservice.model.Country;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CountryRepository extends JpaRepository<Country, String> {
Country findByCountry(String country);
}
鄉村服務.java
package com.example.countriesservice.service;
import java.util.List;
import com.example.countriesservice.model.Country;
import com.example.countriesservice.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CountryService {
private final CountryRepository countryRepository;
@Autowired
public CountryService(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
public List<Country> getAllCountries() {
return countryRepository.findAll();
}
public Country getCountry(String country) {
return countryRepository.findByCountry(country);
}
}
國家控制器.java
package com.example.countriesservice.controller;
import com.example.countriesservice.service.CountryService;
import java.util.List;
import com.example.countriesservice.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/countries")
@RestController
public class CountryController {
private final CountryService countryService;
@Autowired
public CountryController(CountryService countryService) {
this.countryService = countryService;
}
@GetMapping("/getAll")
public List<Country> getAll() {
return countryService.getAllCountries();
}
@GetMapping("/{country}")
public Country getCountry(@PathVariable String country) {
return countryService.getCountry(country);
}
}
輸出

由于我仍在學習 Spring Boot,如果您能詳細解釋一下我做錯了什么以及如何糾正它,那就太好了。
uj5u.com熱心網友回復:
明確提到需要 json 回應。
在CountryController.java 中
import org.springframework.http.MediaType;
@GetMapping(value = "/getAll", produces = { MediaType.APPLICATION_JSON_VALUE })
public List<Country> getAll() {
return countryService.getAllCountries();
}
@GetMapping(value = "/{country}", produces = { MediaType.APPLICATION_JSON_VALUE })
public Country getCountry(@PathVariable String country) {
return countryService.getCountry(country);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/363962.html
上一篇:Java17、Spring啟動測驗、@Sql腳本例外
下一篇:使用JPQL獲取所有關系
