Java.lang.NullPointerException: невозможно вызвать «com.example.demo.UserService.findAll()», поскольку «this.userService ⇐ JAVA

Программисты JAVA общаются здесь
Anonymous
Java.lang.NullPointerException: невозможно вызвать «com.example.demo.UserService.findAll()», поскольку «this.userService

Сообщение Anonymous »

Я новичок в Spring Boot и пытаюсь создать несколько сервисов для вставки, обновления и удаления пользователей, используя отдельный файл JSON. (Функции обновления и удаления должны быть отражены в самом файле json после успешного выполнения.
Когда я пытаюсь запустить URL-адрес «http://localhost:8080/api/users» , возникает следующая ошибка.

Код: Выделить всё

{
"timestamp": "2024-10-23T09:21:37.342+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.NullPointerException: Cannot invoke \"com.example.demo.UserService.findAll()\" because \"this.userService\"  is null\r\n\tat com.example.demo.UserController.getAllUsers(UserController.java:17)\r\n\tat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:580)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:255)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:188)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:926)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:831)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1089)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:195)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:483)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:384)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:905)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1741)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1190)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)\r\n\tat java.base/java.lang.Thread.run(Thread.java:1583)\r\n",
"message": "Cannot invoke \"com.example.demo.UserService.findAll()\" because \"this.userService\"  is null",
"path": "/api/users"
Мой код выглядит следующим образом.
UserService.java

Код: Выделить всё

package com.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

private static final String FILE_PATH = "./Users.json"; // Path to your JSON file
private final ObjectMapper objectMapper = new ObjectMapper();

private List getUsers() throws IOException {
File file = new File(FILE_PATH);
if (file.exists()) {
return objectMapper.readValue(file, objectMapper.getTypeFactory().constructCollectionType(List.class, User.class));
}
return new ArrayList();
}

private void saveUsers(List users) throws IOException {
objectMapper.writeValue(new File(FILE_PATH), users);
}

public List findAll() throws IOException {
return getUsers();
}

public User findById(int userId) throws IOException {
return getUsers().stream()
.filter(user -> user.getUserId() == userId)
.findFirst()
.orElse(null);
}

public void createUser(User newUser) throws IOException {
List users = getUsers();
users.add(newUser);
saveUsers(users);
}

public void updateUser(User updatedUser) throws IOException {
List users = getUsers();
for (User user : users) {
if (user.getUserId() == updatedUser.getUserId()) {
user.setUsername(updatedUser.getUsername());
user.setPassword(updatedUser.getPassword());
user.setName(updatedUser.getName());
user.setCollege(updatedUser.getCollege());
user.setEdited(updatedUser.isEdited());
user.setDeleted(updatedUser.isDeleted());
user.setUserTypeId(updatedUser.getUserTypeId());
break;
}
}
saveUsers(users);
}

public void deleteUser(int userId) throws IOException {
List users = getUsers();
users.removeIf(user -> user.getUserId() == userId);
saveUsers(users);
}

}
UserController.java

Код: Выделить всё

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

private UserService userService;

@GetMapping
public List getAllUsers() throws IOException {
return userService.findAll();
}

@GetMapping("/{id}")
public User getUserById(@PathVariable int id) throws IOException {
return userService.findById(id);
}

@PostMapping
public void createUser(@RequestBody User user) throws IOException {
userService.createUser(user);
}
/*
@PutMapping("/{id}")
public void updateUser(@PathVariable int id, @RequestBody User user) throws IOException {
user.setUserId(id);  // Ensure the user ID is set
userService.updateUser(user);
}*/

@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) throws IOException {
userService.deleteUser(id);
}

}
Пользователь.java

Код: Выделить всё

package com.example.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.fasterxml.jackson.annotation.JsonProperty;

@SpringBootApplication
public class User {
@JsonProperty("userId")
private Long userId;
private String username;
private String password;
private String name;
private String college;
@JsonProperty("is_edited")
private boolean isEdited;
@JsonProperty("is_deleted")
private boolean isDeleted;
@JsonProperty("user_type_id")
private int userTypeId;

public Long getUserId() {
return userId;
}
public void setUserId(String username) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public boolean isEdited() {
return isEdited;
}
public void setEdited(boolean isEdited) {
this.isEdited = isEdited;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public int getUserTypeId() {
return userTypeId;
}
public void setUserTypeId(int userTypeId) {
this.userTypeId = userTypeId;
}
}
ProjApplication.java

Код: Выделить всё

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProjApplication {

public static void main(String[] args) {
SpringApplication.run(User.class, args);
}

}
Может ли кто-нибудь помочь объяснить причину этой ошибки и способы ее устранения?
TIA!

Подробнее здесь: https://stackoverflow.com/questions/791 ... rvice-find

Вернуться в «JAVA»