解决Spring在某些条件下无法自动注入的问题

本文介绍了一个Spring上下文工具类(ContextUtil)的实现方法,该工具类通过ApplicationContextAware接口获取Spring上下文,并提供了一个静态方法getBean用于从上下文中获取指定名称的Bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

静态工具类:

package org.digdata.swustoj.util;

import lombok.Getter;
import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by hongfei.whf on 2016/10/31.
 */
public class ContextUtil implements ApplicationContextAware {

    @Getter
    private static volatile ApplicationContext context = null;

    /**
     * 加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的
     * public void setApplicationContext(ApplicationContext context) throws BeansException
     * & 方法,获得ApplicationContext对象
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * 获取bean
     *
     * @param clazz
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(@NonNull Class<T> clazz, @NonNull String beanName) {
        return (T) context.getBean(beanName);
    }
}

在xml中定义bean

    <!--手动bean定义-->
    <bean class="org.digdata.swustoj.util.ContextUtil"/>

使用示例

    /**
     * 判题队列
     */
    private DefaultJudgeQueue defaultJudgeQueue = ContextUtil.getBean(DefaultJudgeQueue.class, "defaultJudgeQueue");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值