关于@Autowired注入bean为NULL的解决方案(楼主亲测有效,一条语句搞定)

今天遇见这样一个问题,在使用@Autowired注入类的时候,一直报为NULL的空指针的错误。

  1. 错误截图
    这个CommonService是在其他包中定义的。
    那么在另外的包中使用的时候,可能会因为一系列的原因,出现注入失败。
    bean为NULL,总得来说还是加载不到Bean。

在这里插入图片描述

  1. 报错就是空指针
Caused by: java.lang.NullPointerException: null
  1. 解决办法
    新增一个工具类,从Spring的上下文中去取这个Bean.
package com.whalecloud.zsmart.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Classname SpringContextUtil
 * @Description 此工具类用于从Spring的上下文中去获取到类
 * 调用的时候例如:private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);
 * @Date 2019/11/4 2:00 PM
 * @Created by wangdong
 */
@Component
public final class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

}

  1. 在使用的时候
private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);

在这里插入图片描述

好啦,祝您工作顺利。

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以提供一个解决方案。假设我们在使用 Spring 框架和 MySQL 数据库。我们可以通过以下步骤来解决这个问题: 1. 在 Spring 配置文件中增加以下配置,以增加连接池的最大连接数: ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydatabase" /> <property name="user" value="myuser" /> <property name="password" value="mypassword" /> <property name="maxPoolSize" value="20" /> </bean> ``` 上面的配置文件中,我们设置了最大连接数为 20,也就是说,连接池最多维持 20 个连接。 2. 优化应用程序的数据库连接使用方式。例如,我们可以使用连接池来管理数据库连接,避免每次需要连接数据库时都创建一个新的连接。示例代码如下: ``` @Autowired private DataSource dataSource; public void doSomething() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM mytable WHERE id = ?"); stmt.setInt(1, 123); rs = stmt.executeQuery(); while (rs.next()) { // process the result set } } catch (SQLException e) { // handle the exception } finally { try { rs.close(); } catch (Exception e) {} try { stmt.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } } ``` 上面的代码中,我们使用了 Spring 的依赖注入功能来获取数据源对象,然后使用数据源来获取数据库连接。在处理完结果集后,我们关闭了连接、语句和结果集,以释放资源。 通过以上步骤,我们可以解决连接池资源不足的问题,提高应用程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值