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

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....;
	}
}
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值