小谷充电宝项目个人遇到的问题和解决方法

问题一:后端模板导入后,部分依赖无法正常下载

  • 原因:本地仓库没有依赖
  • 解决:新建或者使用其他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: 微信授权登录失败
  • 解决:
  1. share-auth模块调用设置内部调用权限
R<UserInfo> userResult = remoteUserInfoService.wxLogin(code,SecurityConstants.INNER);
  1. 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()方法中,确保在依赖注入完成后再初始化这些属性。具体修改包括:

    1. 将所有依赖于emInfo的字段初始化改为简单声明
    2. 添加@PostConstruct注解的init()方法
    3. 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)

问题十七:门店图片完善

在这里插入图片描述

在这里插入图片描述

React Hooks 是 React 16.8 中新增的特性,它可以让你在函数组件中使用 state、生命周期钩子等 React 特性。使用 Hooks 可以让你写出更简洁、可复用且易于测试的代码。 React Hooks 提供了一系列的 Hook 函数,包括 useState、useEffect、useContext、useReducer、useCallback、useMemo、useRef、useImperativeHandle、useLayoutEffect useDebugValue。每个 Hook 都有特定的用途,可以帮助你处理不同的问题。 下面是 React Hooks 的一些常用 Hook 函数: 1. useState useState 是最常用的 Hook 之一,它可以让你在函数组件中使用 state。useState 接受一个初始状态值,并返回一个数组,数组的第一个值是当前 state 值,第二个值是更新 state 值的函数。 ``` const [count, setCount] = useState(0); ``` 2. useEffect useEffect 可以让你在组件渲染后执行一些副作用操作,比如订阅事件、异步请求数据等。useEffect 接受两个参数,第一个参数是一个回调函数,第二个参数是一个数组,用于控制 useEffect 的执行时机。 ``` useEffect(() => { // 这里可以执行副作用操作 }, [dependencies]); ``` 3. useContext useContext 可以让你在组件树中获取 context 的值。它接受一个 context 对象,并返回该 context 的当前值。 ``` const value = useContext(MyContext); ``` 4. useRef useRef 可以让你在组件之间共享一个可变的引用。它返回一个对象,该对象的 current 属性可以存储任何值,并在组件的生命周期中保持不变。 ``` const ref = useRef(initialValue); ref.current = value; ``` 5. useCallback useCallback 可以让你缓存一个函数,以避免在每次渲染时都创建一个新的函数实例。它接受一个回调函数一个依赖数组,并返回一个 memoized 的回调函数。 ``` const memoizedCallback = useCallback(() => { // 这里是回调函数的逻辑 }, [dependencies]); ``` 6. useMemo useMemo 可以让你缓存一个计算结果,以避免在每次渲染时都重新计算。它接受一个计算函数一个依赖数组,并返回一个 memoized 的计算结果。 ``` const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); ``` 以上就是 React Hooks 的一些常用 Hook 函数,它们可以帮助你更好地处理组件状态、副作用、上下文性能优化等问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值