Static 静态变量 不能直接使用 @autowired标签的问题

本文探讨了在Spring框架中,如何解决静态变量无法直接使用@Autowired注解进行依赖注入的问题。提供了两种解决方案:一是通过自定义工具类实现ApplicationContextAware接口,使用applicationContext.getBean方法获取Bean;二是将需要注入的Bean声明为静态变量并通过set方法注入。

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

1、问题原因
被static修饰变量,是不属于任何实例化的对象拥有,spring的依赖注入只能在对象层级上进行依赖注入,所以不能直接使用@autowired标签进行注入。

2.解决方案
①在静态方法中使自定义的工具类,该工具类实现ApplicationContextAware ,在该工具类中通过applicationContext.getBean 来获取想要的bean类。

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String beanName) {

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

        try {
            return applicationContext.getBean(beanName);
        }
        catch (NullPointerException e)
        {
            return null;
        }
    }
    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }
}

②使用@autowired 标签进行set方法注入。具体为,将需要注入的bean申明为静态的全局变量, 在通过set方法注入,在静态方法中就能直接使用该变量。例如下面描述的 在静态方法中dosomething中想要使用bean类 MyTestBean.

@Component
public class Myclass{

	private static MyTestBean mytestbean;

	@Autowired
	public void setMyTestBean(MyTestBean mytestbean){
		Myclass.mytestbean=mytestbean;
	}

	public static void dosomething(){
		mytestbean....;
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值