ПациентСервис
@Path("/patientservice")
public interface PatientService {
@Path("/patients")
@GET
List<Patient> getPatients();
}
PatientServiceImpl
@Service
public class PatientServiceImpl implements PatientService {
Map<Long, Patient> patients = new HashMap<>();
long currentId = 123;
public PatientServiceImpl() {
init();
}
void init() {
Patient patient = new Patient();
patient.setId(currentId);
patient.setName("John");
patients.put(patient.getId(), patient);
}
@Override
public List<Patient> getPatients() {
Collection<Patient> results = patients.values();
List<Patient> response = new ArrayList<>(results);
return response;
}
}
Я пытался использовать удары localhost: 8080 / услуги / обслуживание пациентов / пациенты / и localhost: 8080 / обслуживание пациентов / пациенты / как URL-адреса, но по-прежнему отображается экран ошибки 404. Не могли бы вы помочь мне отладить, что может быть не так с кодом? Приложение работает нормально, без ошибок.
pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bharath.restws</groupId>
<artifactId>restws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>restws</name>
<description>Patient REST Services</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.1.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Можете ли вы показать свой файл pom.xml или build.gradle?




Похоже, вам нужен контроллер, который будет обрабатывать запросы
@RestController
public class PatientController {
@GetMapping("/patients")
List<PatientModel> getPatients() {
return Arrays.asList(
new PatientModel("1", "john"),
new PatientModel("2", "donald")
);
}
static class PatientModel {
private String id;
private String name;
// constructor, getters, setters
}
}
Поэтому, когда вы запрашиваете пациентов с curl http://localhost:8080/patients, он вернет вам список [{"id":"1","name":"john"},{"id":"2","name":"donald"}].
и в этом контроллере вы можете использовать любые сервисы сверху, которые вы реализовали
Я думаю, что вы хотите, чтобы REST controller перехватил ваш запрос и отправил в вашу службу.
Сначала добавьте Qualifier в свою реализацию интерфейса PatientService, чтобы мы могли автоматически подключить его к контроллеру.
@Service
@Qualifier("myImplementation")
public class PatientServiceImpl implements PatientService {
// your code goes here
}
Затем создайте свой контроллер REST
@RestController
public class PatientController {
@Autowired
@Qualifier("myImplementation")
PatientService patientService;
@RequestMapping("/patients")
public List<Patient> getPatients() {
List<Patient> patients = patientServiceImpl.getPatients();
return patients;
}
}
Теперь ваша конечная точка /patients сопоставлена с методом getPatients() контроллера. Это, в свою очередь, вызовет метод службы и вернет результат.
Используя вашу реализацию PatientServiceImpl, вызов http://localhost:8080/patients возвращает
[{"id":123,"name":"John"}]
Переформатируйте свой код и предоставьте немного больше информации о том, чего вы пытаетесь достичь и в чем именно заключается проблема. В общем, проблема очевидна, но вы должны сделать ее правильным вопросом.