工具类中引用Spring IOC容器对象的处理方案

在工具类中引用Spring IOC容器的静态方法时,会遇到非静态字段不能在静态上下文中引用的问题。解决方案包括将对象作为方法参数传递,但这在方法多的情况下不理想,或者在调用时使用ApplicationContext.getBean()初始化。可以通过在特定阶段调用ApplicationContext的初始化钩子方法解决此问题,如在ware阶段。示例代码展示了如何通过内部类获取RedisTemplate对象。
摘要由CSDN通过智能技术生成

前言

我们在工具类中引入spring ioc容器中,在static 方法中使用需要使用。放在该ioc容器上面报Non-static field ‘jedisCluster’ cannot be referenced from a static context 这种错误。这个是因为spring 初始化容器的速度,可能会慢于工具类报错的速度导致该方法调用失败。

实践

我们遇到这种问题,一般会有两种方案。第一个是将该对象作为方法调用传参使用。特别是当该工具类的使用普遍、方法比较多的情况显得很麻烦。第二种、通过调用的时候利用ApplicationContext.getBean() 的方式进行初始化。这个利用到spring ioc容器的时候调用勾子方法来对ApplicationContext 初始化。

在这里插入图片描述

我们这里就在ware 这个阶段调用ApplicationContext 对应勾子方法对其进行初始化。
代码:

@Component
public class SpringUtils implements ApplicationContextAware {
   

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
   
        return applicationContext;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) {
   
        SpringUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
   
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
   
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
   
        return applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
   
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
   
        return applicationContext.isSingleton(name);
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值