- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的第三个个人 spring-boot 项目,我所做的配置与之前的 99% 相同,所以不知道为什么我会在这个项目上遇到此错误。
项目启动得很好,但是一旦我对我拥有的唯一的 @RestController 进行任何请愿,它就会立即收到 null 错误。该端点接收一个 alpha 2 国家/地区代码 + 城市名称 + 所需的 ip 地址,如果未提供 ip 地址,它将采用客户端 ip 地址,该地址用作我从中获取 null 的 @Service 的参数。之后, Controller 应该在将预期输出发送到客户端之前执行许多其他操作,但由于此 @Service 上出现 null 异常,它永远不会达到该点。
这是我正在尝试的请愿书:
http://localhost:8080/apiv1/get-distance?country=af&city=Qalat&ip=150.135.184.38
There was an unexpected error (type=Internal Server Error, status=500).
Cannot invoke "me.givo.distancebetweenus.getdistance.services.CurrentLocationService.getCurrentLocation(String)" because "this.currentLocationService" is null
java.lang.NullPointerException: Cannot invoke "me.givo.distancebetweenus.getdistance.services.CurrentLocationService.getCurrentLocation(String)" because "this.currentLocationService" is null
at me.givo.distancebetweenus.getdistance.controllers.DistanceController.getDistance(DistanceController.java:53)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
这是我的 Controller :
package me.givo.distancebetweenus.getdistance.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import me.givo.distancebetweenus.getdistance.dtos.CityDto;
import me.givo.distancebetweenus.getdistance.dtos.CountryDto;
import me.givo.distancebetweenus.getdistance.entities.CityEntity;
import me.givo.distancebetweenus.getdistance.entities.CountryEntity;
import me.givo.distancebetweenus.getdistance.models.ApiCurrentLocationResponse;
import me.givo.distancebetweenus.getdistance.models.Coordinate;
import me.givo.distancebetweenus.getdistance.models.DistanceResponse;
import me.givo.distancebetweenus.getdistance.repositories.ICitiesRepository;
import me.givo.distancebetweenus.getdistance.repositories.ICountriesRepository;
import me.givo.distancebetweenus.getdistance.services.CurrentLocationService;
import org.modelmapper.ModelMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/apiv1")
@Validated
@RestController
public class DistanceController {
private final CurrentLocationService currentLocationService;
private final ICitiesRepository citiesRepository;
private final ICountriesRepository countriesRepository;
private final ModelMapper modelMapper;
public DistanceController(CurrentLocationService currentLocationService, ICitiesRepository citiesRepository,
ICountriesRepository countryRepository, ModelMapper modelMapper) {
this.currentLocationService = currentLocationService;
this.citiesRepository = citiesRepository;
this.countriesRepository = countryRepository;
this.modelMapper = modelMapper;
}
@GetMapping("/get-distance")
@ResponseBody
private ResponseEntity<Object> getDistance(
@RequestParam(required = true, name = "country") @Min(2) @Max(2) String country,
@RequestParam(required = true, name = "city") String city,
@RequestParam(required = false, name = "ip") @Min(7) @Max(15) String ip,
HttpServletRequest request) {
ApiCurrentLocationResponse currentLocation;
if (ip == null || ip.isEmpty()) {
String requestIP = request.getRemoteAddr();
System.out.println(requestIP);
try {
currentLocation = currentLocationService.getCurrentLocation(requestIP);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else {
try {
currentLocation = currentLocationService.getCurrentLocation(ip);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
CountryEntity countryEntity = countriesRepository.getById(country);
CityEntity cityEntity = citiesRepository.getByNameAndCode(city, country);
CountryDto countryDto = convertToCountryDto(countryEntity);
CityDto cityDto = convertToCityDto(cityEntity);
Coordinate currentLocationCoordinate = new Coordinate(currentLocation);
Coordinate destinationCoordinate = new Coordinate(cityDto);
Double distance = currentLocationCoordinate.distanceBetweenUsKm(destinationCoordinate);
DistanceResponse response = new DistanceResponse(countryDto, cityDto, distance);
return ResponseEntity.status(HttpStatus.OK).body(response);
}
private CityDto convertToCityDto(CityEntity cityEntity) {
return modelMapper.map(cityEntity, CityDto.class);
}
private CountryDto convertToCountryDto(CountryEntity countryEntity) {
return modelMapper.map(countryEntity, CountryDto.class);
}
}
这是“null”@Service:
package me.givo.distancebetweenus.getdistance.services;
import me.givo.distancebetweenus.getdistance.models.ApiCurrentLocationResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class CurrentLocationService {
private final WebClient.Builder webClient;
private final String key = "fakekey347834834892923fake";
public CurrentLocationService(WebClient.Builder webClient) {
this.webClient = webClient;
}
public ApiCurrentLocationResponse getCurrentLocation(String requestIP) {
String url = "https://api.fakeapi.app/json/";
return webClient.baseUrl(url).build().get()
.uri(uriBuilder -> uriBuilder
.path(requestIP)
.queryParam("apikey", key)
.build())
.retrieve()
.bodyToMono(ApiCurrentLocationResponse.class)
.block();
}
}
非常感谢您的帮助。如果需要任何其他信息,请告诉我。谢谢你! - - - - - - - - 编辑 - - - - - - - - - - shivam 的评论给了我在注入(inject)中使用 @Autowired 标记的想法,所以我这样做了,并且我不再在 @Service 中收到 null 异常,它位于 ICountriesRepository 中,而这只是我的 @RestController 中的下一行代码..这些是我所做的更改:
public class DistanceController {
private final CurrentLocationService currentLocationService;
private final ICitiesRepository citiesRepository;
private final ICountriesRepository countriesRepository;
private final ModelMapper modelMapper;
@Autowired
public DistanceController(CurrentLocationService currentLocationService, ICitiesRepository citiesRepository,
ICountriesRepository countriesRepository, ModelMapper modelMapper) {
this.currentLocationService = currentLocationService;
this.citiesRepository = citiesRepository;
this.countriesRepository = countriesRepository;
this.modelMapper = modelMapper;
}
这是"new"错误日志:
There was an unexpected error (type=Internal Server Error, status=500).
Cannot invoke "me.givo.distancebetweenus.getdistance.repositories.ICountriesRepository.getById(Object)" because "this.countriesRepository" is null
java.lang.NullPointerException: Cannot invoke "me.givo.distancebetweenus.getdistance.repositories.ICountriesRepository.getById(Object)" because "this.countriesRepository" is null
at me.givo.distancebetweenus.getdistance.controllers.DistanceController.getDistance(DistanceController.java:72)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
这是 ICountriesRepository 的代码:
package me.givo.distancebetweenus.getdistance.repositories;
import me.givo.distancebetweenus.getdistance.entities.CountryEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ICountriesRepository extends JpaRepository<CountryEntity, String> {
}
另外,我添加了为 ModelMapper 制作的 @Configuration 代码:
package me.givo.distancebetweenus.getdistance.config;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
最佳答案
我在工作日有点忙,所以直到现在才能够检查我的代码,我发现我的 Controller 拥有的唯一 GetMapping 方法是私有(private)。我刚刚将其公开,并且一切都已按预期运行。感谢大家抽出时间。
关于java - 使用构造函数注入(inject)的 spring @RestController 中的空异常 @Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70143003/
问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionally与 CompletableFuture#supplyAsync 一起.这是行不通的: priva
对于 Web 服务,我们通常使用 maven-jaxb2-plugin 生成 java bean,并在 Spring 中使用 JAXB2 编码。我想知道如何处理 WSDL/XSD 中声明的(SOAP-
这个问题已经有答案了: Array index out of bound behavior (10 个回答) 已关闭 8 年前。 我对下面的 C 代码感到好奇 int main(){
当在类的开头使用上下文和资源初始化 MediaPlayer 对象时,它会抛出 NullPointer 异常,但是当在类的开头声明它时(因此它是 null),然后以相同的方式初始化它在onCreate方
嘿 我尝试将 java 程序连接到 REST API。 使用相同的代码部分,我在 Java 6 中遇到了 Java 异常,并且在 Java 8 中运行良好。 环境相同: 信任 机器 unix 用户 代
我正在尝试使用 Flume 和 Hive 进行 Twitter 分析。为了从 twitter 获取推文,我在 flume.conf 文件中设置了所有必需的参数(consumerKey、consumer
我在 JavaFX 异常方面遇到一些问题。我的项目在我的 Eclipse 中运行,但现在我的 friend 也尝试访问该项目。我们已共享并直接保存到保管箱文件夹中。但他根本无法让它发挥作用。他在控制台
假设我使用 blur() 事件验证了电子邮件 ID,我正在这样做: $('#email').blur(function(){ //make ajax call , check if dupli
我这样做是为了从 C 代码调用非托管函数。 pCallback 是一个函数指针,因此在托管端是一个委托(delegate)。 [DllImport("MyDLL.dll")] public stati
为什么这段代码是正确的: try { } catch(ArrayOutOfBoundsException e) {} 这是错误的: try { } catch(IOException e) {} 这段
我遇到了以下问题:有导出函数的DLL。 代码示例如下:[动态链接库] __declspec(dllexport) int openDevice(int,void**) [应用] 开发者.h: __de
从其他线程,我知道我们不应该在析构函数中抛出异常!但是对于下面的例子,它确实有效。这是否意味着我们只能在一个实例的析构函数中抛出异常?我们应该如何理解这个代码示例! #include using n
为什么需要异常 引出 public static void main(String[
1. Java的异常机制 Throwable类是Java异常类型的顶层父类,一个对象只有是 Throwable 类的(直接或者间接)实例,他才是一个异常对象,才能被异常处理机制识别。JDK中内
我是 Python 的新手,我对某种异常方法的实现有疑问。这是代码(缩写): class OurException(Exception): """User defined Exception"
我已经创建了以下模式来表示用户和一组线程之间的关联,这些线程按他们的最后一条消息排序(用户已经阅读了哪些线程,哪些没有): CREATE TABLE table(user_id bigint, mes
我正在使用 Python 编写一个简单的自动化脚本,它可能会在多个位置引发异常。在他们每个人中,我都想记录一条特定的消息并退出程序。为此,我在捕获异常并处理它(执行特定的日志记录操作等)后引发 Sys
谁能解释一下为什么这会导致错误: let xs = [| "Mary"; "Mungo"; "Midge" |] Array.iter printfn xs 虽然不是这样: Array.iter pr
在我使用 Play! 的网站上,我有一个管理部分。所有 Admin Controller 都有一个 @With 和一个 @Check 注释。 断开连接后,一切正常。连接后,每次加载页面(任何页面,无论
我尝试连接到 azure 表存储并添加一个对象。它在本地主机上工作得很好,但是在我使用的服务器上我得到以下异常及其内部异常: Exception of type 'Microsoft.Wind
我是一名优秀的程序员,十分优秀!