文章目录
- 问题一:后端模板导入后,部分依赖无法正常下载
- 问题二:启动找不到主类
- 问题三:前端验证码无法显示
- 问题四:数据库驱动不合适
- 问题五:MongoDB连接失败
- 问题六:ShareUserApplication启动失败
- 问题七:微信登录失败
- 问题八:服务端口占用
- 问题九:进程假死
- 问题十:onMessageCallback未定义
- 问题十一:shareOrderApplication启动报错
- 问题十二:rabbitConnectionFactory创建失败
- 问题十三:share-file模块启动报错连接redis失败
- 问题十四:小程序扫码之后,柜机解锁,前端报错
- 问题十五:SQL语法错误
- 问题十六:share-statics模块启动报错
- 问题十七:门店图片完善
问题一:后端模板导入后,部分依赖无法正常下载
- 原因:本地仓库没有依赖
- 解决:新建或者使用其他springboot项目,导入依赖将下载依赖到本地仓库,然后项目模板依赖就正常加载出来了!
- 说明:本解决方案,完全基于突发灵感,实践后总结而来
问题二:启动找不到主类
- 解决办法:不要修改项目模板的目录名称
问题三:前端验证码无法显示
- share-parent/share-ui/vite.config.js修改后端接口地址
proxy: {
'/dev-api': {
target: 'http://localhost:18080',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/dev-api/, '')
}
}
问题四:数据库驱动不合适
- 解决:
- 数据库版本:mysql8.0
- 数据库驱动:
com.mysql.cj.jdbc.Driver
问题五:MongoDB连接失败
- 解决:修改nacos配置文件
# mongodb配置
spring:
data:
mongodb:
host: 192.168.171.128
port: 27017
database: share #指定操作的数据库
username: mongo
password: mongo_Qr7625
authentication-database: admin
问题六:ShareUserApplication启动失败
00:40:14.329 [main] WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - [refresh,592] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.share.common.log.aspect.LogAspect': Injection of resource dependencies failed
00:40:14.332 [main] INFO o.a.c.c.StandardService - [log,173] - Stopping service [Tomcat]
00:40:14.403 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - [report,40] -
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.share.system.api.RemoteLogService' that could not be found.
Action:
Consider defining a bean of type 'com.share.system.api.RemoteLogService' in your configuration.
- 解决方法:
ShareUserApplication
添加注解
@EnableCustomConfig
@EnableRyFeignClients
@SpringBootApplication
问题七:微信登录失败
- 原因:内部远程调用错误访问权限,不允许访问
00:37:54.461 [boundedElastic-1] INFO c.a.n.client.naming - [processServiceInfo,169] - current ips:(1) service: DEFAULT_GROUP@@share-user -> [{"instanceId":"192.168.171.1#9209#DEFAULT#DEFAULT_GROUP@@share-user","ip":"192.168.171.1","port":9209,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"DEFAULT","serviceName":"DEFAULT_GROUP@@share-user","metadata":{"preserved.register.source":"SPRING_CLOUD","IPv6":"[240e:33d:c3a:c00:b919:a7aa:b58d:55a1]"},"ipDeleteTimeout":30000,"instanceHeartBeatTimeOut":15000,"instanceHeartBeatInterval":5000}]
【小程序授权】userResult=com.share.common.core.domain.R@de12005
【小程序授权】userResult=没有内部访问权限,不允许访问
【小程序授权】userResult=null
【小程序授权】userResult=500
00:37:54.551 [http-nio-9200-exec-1] ERROR c.s.c.s.h.GlobalExceptionHandler - [handleServiceException,71] - 微信授权登录失败
com.share.common.core.exception.ServiceException: 微信授权登录失败
- 解决:
- share-auth模块调用设置内部调用权限
R<UserInfo> userResult = remoteUserInfoService.wxLogin(code,SecurityConstants.INNER);
- share-api-user模块设置内部调用权限
@GetMapping("/userInfo/wxLogin/{code}")
R<UserInfo> wxLogin(@PathVariable("code") String code,@RequestHeader(SecurityConstants.FROM_SOURCE) String source);
问题八:服务端口占用
- 问题:端口被占用
Web server failed to start. Port 9200 was already in use.
- 解决:杀死进程
(base) PS C:\Windows\system32> netstat -ano | findstr :9200
TCP 0.0.0.0:9200 0.0.0.0:0 LISTENING 4652
TCP [::]:9200 [::]:0 LISTENING 4652
(base) PS C:\Windows\system32> tasklist | findstr 4652
java.exe 4652 Console 1 604,088 K
(base) PS C:\Windows\system32> taskkill /PID 4652 /F
成功: 已终止 PID 为 4652 的进程。
问题九:进程假死
Web server failed to start. Port 9200 was already in use.
- 解决:进入任务管理器,手动结束idea进程下的假死进程,再启动项目,或者终止项目,退出idea,重启电脑
问题十:onMessageCallback未定义
13:32:12.348 [main] ERROR o.s.b.SpringApplication - [reportFailure,822] - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'onMessageCallback' defined in file [D:\code\PowerBankSystem\share-parent\share-modules\share-device\target\classes\com\share\device\emqx\callBack\OnMessageCallback.class]: Failed to instantiate [com.share.device.emqx.callBack.OnMessageCallback]: Constructor threw exception
13:32:12.354 [Thread-1] WARN c.a.n.c.h.HttpClientBeanHolder - [shutdown,102] - [HttpClientBeanHolder] Start destroying common HttpClient
13:32:12.354 [Thread-7] WARN c.a.n.c.n.NotifyCenter - [shutdown,136] - [NotifyCenter] Start destroying Publisher
13:32:12.354 [Thread-7] WARN c.a.n.c.n.NotifyCenter - [shutdown,153] - [NotifyCenter] Destruction of the end
-
问题:错误显示为NullPointerException,原因是在构造函数中尝试访问emInfo属性(通过emInfo.getServerURI()等)时,emInfo还未被Spring注入。这是因为字段初始化发生在依赖注入之前。在OnMessageCallback类中。在Spring Bean的生命周期中,字段注入(@Resource)发生在Bean实例化之后,但当前代码在字段声明时就直接使用了emInfo的方法,此时emInfo还未被注入,导致NullPointerException。
-
解决方案:将这些属性的初始化从字段声明处移到了@PostConstruct注解标记的init()方法中,确保在依赖注入完成后再初始化这些属性。具体修改包括:
- 将所有依赖于
emInfo
的字段初始化改为简单声明 - 添加
@PostConstruct
注解的init()
方法 - 在
init()
方法中完成所有属性的初
- 将所有依赖于
@Resource
private EmqxProperties emInfo;
private MqttClient client;
private String brokerUrl;
private String clientId;
private String userName;
private String password;
private int maxReconnectAttempts; // 最大重试次数
private int reconnectDelay; // 初始重连延迟(毫秒)
private int currentAttempts = 0; // 当前重试次数
@jakarta.annotation.PostConstruct
private void init() {
// 在依赖注入完成后初始化属性
this.brokerUrl = emInfo.getServerURI();
this.clientId = emInfo.getClientId();
this.userName = emInfo.getUsername();
this.password = emInfo.getPassword();
this.maxReconnectAttempts = emInfo.getMaxReconnectAttempts();
this.reconnectDelay = emInfo.getReconnectDelay();
}
- 使用@Autowired注解也会出现同样的问题。问题的根本原因不是使用哪种依赖注入注解,而是在Spring Bean的生命周期中,依赖注入(无论是@Resource还是@Autowired)都发生在Bean实例化之后。如果在字段声明时就直接使用了emInfo的方法(如emInfo.getServerURI()),此时emInfo还未被注入,就会导致NullPointerException。
- 正确的做法是将依赖于emInfo的初始化逻辑放在@PostConstruct注解的方法中
问题十一:shareOrderApplication启动报错
18:57:44.476 [main] WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - [refresh,592] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderInfoApiController': Injection of resource dependencies failed
18:57:44.478 [main] INFO o.a.c.c.StandardService - [log,173] - Stopping service [Tomcat]
18:57:44.565 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - [report,40] -
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.share.rules.api.RemoteFeeRuleService' that could not be found.
Action:
Consider defining a bean of type 'com.share.rules.api.RemoteFeeRuleService' in your configuration.
18:57:44.568 [Thread-1] WARN c.a.n.c.h.HttpClientBeanHolder - [shutdown,102] - [HttpClientBeanHolder] Start destroying common HttpClient
18:57:44.568 [Thread-7] WARN c.a.n.c.n.NotifyCenter - [shutdown,136] - [NotifyCenter] Start destroying Publisher
18:57:44.569 [Thread-7] WARN c.a.n.c.n.NotifyCenter - [shutdown,153] - [NotifyCenter] Destruction of the end
- 通过分析错误日志和代码,发现问题出在ShareOrderApplication类缺少必要的Feign客户端配置。
- 在ShareOrderApplication类中添加了以下关键注解:
- @EnableCustomConfig:启用自定义配置
- @EnableRyFeignClients:启用Feign客户端支持
问题十二:rabbitConnectionFactory创建失败
- ShareDeviceApplication启动报错
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'rabbitConnectionFactory': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!) 22:50:10.320 [main] WARN o.s.c.a.AnnotationConfigApplicationContext - [doClose,1039] - Exception thrown from ApplicationListener handling ContextClosedEvent org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'rabbitConnectionFactory': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
- 解决:从别的类似模块复制文件修改内容,使其识别为springboot项目文件,内容如下
com.share.common.rabbit.service.RabbitService
com.share.common.rabbit.config.RabbitInitConfigApplicationListener
问题十三:share-file模块启动报错连接redis失败
- nacos配置文件中添加redis配置
spring:
data:
redis:
host: 192.168.171.128
port: 6379
password: redis_85BAbp
问题十四:小程序扫码之后,柜机解锁,前端报错
TypeError: Cannot read property 'id' of undefined
at _callee$ (index.js? [sm]:66)
at s (regeneratorRuntime.js?forceSync=true:1)
at Generator.<anonymous> (regeneratorRuntime.js?forceSync=true:1)
at Generator.next (regeneratorRuntime.js?forceSync=true:1)
at asyncGeneratorStep (asyncToGenerator.js?forceSync=true:1)
at c (asyncToGenerator.js?forceSync=true:1)(env: Windows,mp,1.06.2412050; lib: 3.6.4)
- 请具体分析,然后去仓库查看我的相关文件,仓库地址
问题十五:SQL语法错误
00:36:59.105 [http-nio-9205-exec-4] ERROR c.s.c.s.h.GlobalExceptionHandler - [handleRuntimeException,105] - 请求地址'/device/scanCharge/gj001',发生未知异常.
org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND status = '1')' at line 4
### The error may exist in com/share/device/mapper/PowerBankMapper.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT id,power_bank_no,electricity,description,status,create_by,create_time,update_by,update_time,remark,del_flag FROM power_bank WHERE del_flag='0' AND (id IN () AND status = ?)
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND status = '1')' at line 4
; bad SQL grammar []
- 解决方法:
src/main/java/com/share/device/mapper/PowerBankMapper.java
<select id="selectPowerBankList" parameterType="PowerBank" resultMap="PowerBankResult">
<include refid="selectPowerBankVo"/>
<where>
<if test="powerBankNo != null and powerBankNo != ''">and power_bank_no = #{powerBankNo}</if>
<if test="electricity != null ">and electricity = #{electricity}</if>
<if test="description != null and description != ''">and description = #{description}</if>
<if test="status != null and status != ''">and status = #{status}</if>
and del_flag = 0
</where>
</select>
问题十六:share-statics模块启动报错
- 错误:提示找不到数据源地址配置
2025-04-13T18:13:32.964+08:00 INFO 37292 --- [ main] o.s.c.openfeign.FeignClientFactoryBean : For 'share-user' URL not provided. Will try picking an instance via load-balancing.
2025-04-13T18:13:36.764+08:00 INFO 37292 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2025-04-13T18:13:38.529+08:00 INFO 37292 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2025-04-13T18:13:38.582+08:00 WARN 37292 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class
2025-04-13T18:13:38.586+08:00 INFO 37292 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2025-04-13T18:13:38.615+08:00 INFO 37292 --- [ main] .s.b.a.l.ConditionEvaluationReportLogger :
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2025-04-13T18:13:38.654+08:00 ERROR 37292 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (the profiles dev are currently active).
- 解决方法:启动类添加注解排除数据源自动配置
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)