springboot静态工具类bean注入

工具类中调用数据。但是由于工具类方法一般都写成static,所以直接注入就存在问题。

所以写成了这样:

package com.rm.framework.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.PostConstruct;

@Component
public class RivuDataContext {

	/** 应用上下文 */
	public static String webRoot = "/r3";
	/** 应用上下文 */
	public static String cookieNameLoginToken = "LoginToken";
	
	/** 当前线程用户名 */
	public final static String USER_SESSION_NAME = "curUser";
	
	/** spring上下文 */
	@Autowired
	private  ConfigurableApplicationContext applicationContext;

	private static 	RivuDataContext rivuDataContext;

	@PostConstruct
	public void init() {
		rivuDataContext = this;
		rivuDataContext.applicationContext = this.applicationContext;

	}

	public static void setApplicationContext(ConfigurableApplicationContext webApplicationContext) {
		rivuDataContext.applicationContext= webApplicationContext;
	}

	public static ConfigurableApplicationContext getApplicationContext() {
		return rivuDataContext.applicationContext;
	}
	
	public static Object getBean(String beanName){
		return rivuDataContext.applicationContext.getBean(beanName);
	}
}

  

转载于:https://www.cnblogs.com/q1359720840/articles/10912466.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,静态类中使用注入需要借助Spring提供的工具类`ApplicationContextAware`。具体步骤如下: 1. 定义一个静态类,实现`ApplicationContextAware`接口,重写`setApplicationContext()`方法。 ```java public class StaticClass implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { StaticClass.applicationContext = applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } } ``` 2. 在静态类中定义一个静态成员变量`applicationContext`,用于保存ApplicationContext对象。 3. 在`setApplicationContext()`方法中,将ApplicationContext对象保存到静态成员变量`applicationContext`中。 4. 在静态类中定义一个静态方法`getBean(String name)`,用于获取Bean实例。 5. 在静态方法中使用静态成员变量`applicationContext`获取Bean实例。 例如,我们要在静态类中使用`UserService`进行业务操作,可以使用如下代码: ```java public class StaticClass implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { StaticClass.applicationContext = applicationContext; } public static UserService getUserService() { return applicationContext.getBean(UserService.class); } } ``` 这样,我们就可以在静态类中使用注入Bean实例了。注意,使用静态类中的注入需要保证Spring容器已经启动,否则可能会出现空指针异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值