spring给静态成员注入 你试过吗?

给静态成员注入 你试过吗?

public class TempDataTransformUtilDto {
	@Autowired
    private static ICityCascadeService cityCascadeService;

    private static CstShareEmpMapper cstShareEmpMapper;
	
    private static PubUserInfoMapper pubUserInfoMapper;
}

如果ICityCascadeService 通过@Service 注入的,@Autowired在这里是不管用的。

在使用时 会报错NullPointer !!!

理解:

1.类成员的初始化较早,并不需要依赖实例的创建,所以这个时候Spring容器可能都还没“出生”,谈何依赖注入呢?

2.当类加载器加载静态变量时,Spring的上下文环境还没有被加载。

3.AutowiredAnnotationBeanPostProcessor类源码,扫描Class类需要注入的元数据的时候,直接选择忽略掉了static成员(包括属性和方法)。

AutowiredAnnotationBeanPostProcessor// 构建@Autowired注入元数据方法
// 简单的说就是找到该Class类下有哪些是需要做依赖注入的
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
	...
	// 循环递归,因为父类的也要管上
	do {
		// 遍历所有的字段(包括静态字段)
		ReflectionUtils.doWithLocalFields(targetClass, field -> {
			if (Modifier.isStatic(field.getModifiers())) {
				logger.info("Autowired annotation is not supported on static fields: " + field);
			}
			return;
			...
		});
		// 遍历所有的方法(包括静态方法)
		ReflectionUtils.doWithLocalMethods(targetClass, method -> {
			if (Modifier.isStatic(method.getModifiers())) {
				logger.info("Autowired annotation is not supported on static methods: " + method);
			}
			return;
			...
		});
		...
		targetClass = targetClass.getSuperclass();
	} while (targetClass != null && targetClass != Object.class);
	...
静态变量(成员)它是属于类的,而非属于实例对象的属性;
同样的静态方法也是属于类的,普通方法(实例方法)才属于对象。而Spring容器管理的都是实例对象

但是有时候 我们会想要去注入到静态成员 比如在工具类中使用static方法,这时我们就需要使用static属性,而这些属性又必须注入。

所以说 spring是不会去注入的,需要我们自己想办法~~ 也就是等实例都创建好了 再自己注入

解决方案一:使用@PostConstruct注解

@PostConstruct用来修饰一个非静态的void方法,当bean创建完成的时候,会后置执行@PostConstruct修饰的方法,并且只运行一次。

可以将static变量延迟初始化,在能够注入后进行初始化。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RedisUtil {

private static RedisTemplate<Object, Object> redisTemplates;

@Autowired
private RedisTemplate<Object, Object> redisTemplate;

@PostConstruct
public void initialize() {
    redisTemplates = this.redisTemplate;
}

/**
 * 添加元素
 *
 * @param key
 * @param value
 */
public static void set(Object key, Object value) {

    if (key == null || value == null) {
        return;
    }
    redisTemplates.opsForValue().set(key, value);
}

存在的问题:得保证在bean初始化之前,这个工具类的static方法不会被调用。

方法二:

写一个构造方法

@Component
public class TempDataTransformUtilDto {

    private static ICityCascadeService cityCascadeService;

    private static CstShareEmpMapper cstShareEmpMapper;

    private static PubUserInfoMapper pubUserInfoMapper;

    private static CustPersonMapper custPersonMapper;

    private static CstOrganizationMapper cstOrganizationMapper;

    private static CustBaseInfoMapper custBaseInfoMapper;

    @Autowired
    public TempDataTransformUtilDto(ICityCascadeService cityCascadeService, CstShareEmpMapper cstShareEmpMapper, PubUserInfoMapper pubUserInfoMapper
            ,CustPersonMapper custPersonMapper,CstOrganizationMapper cstOrganizationMapper,CustBaseInfoMapper custBaseInfoMapper) {
        TempDataTransformUtilDto.cityCascadeService = cityCascadeService;
        TempDataTransformUtilDto.cstShareEmpMapper = cstShareEmpMapper;
        TempDataTransformUtilDto.pubUserInfoMapper = pubUserInfoMapper;
        TempDataTransformUtilDto.custPersonMapper = custPersonMapper;
        TempDataTransformUtilDto.cstOrganizationMapper = cstOrganizationMapper;
        TempDataTransformUtilDto.custBaseInfoMapper = custBaseInfoMapper;
    }

方法三:

不再需要标注@Component注解

public class UserHelper {

    static UCClient ucClient;
    @Autowired
    public void setUcClient(UCClient ucClient) {
        UserHelper.ucClient = ucClient;
    }
}
  1. 手动管理这种case的依赖注入,更可控。而非交给Spring容器去自动处理
  2. 工具类本身并不需要加入到Spring容器内,这对于有大量这种case的话,是可以节约开销的

参考

在工具类中使用静态成员进行依赖注入是一个常见的需求,但需要注意的是,静态成员本身并不支持依赖注入框架(如Spring)的自动注入。因此,我们需要采用一些特殊的方法来实现这一目标。以下是几种常见的方法: 1. **构造函数注入**: 通过构造函数将依赖注入到工具类中,然后将依赖赋值给静态成员。这种方法需要将工具类设计为非单例模式,或者在每次使用前进行实例化。 ```java public class MyUtils { private static MyDependency myDependency; public MyUtils(MyDependency myDependency) { MyUtils.myDependency = myDependency; } public static void doSomething() { myDependency.performAction(); } } ``` 2. **Setter方法注入**: 通过Setter方法将依赖注入到工具类中,然后将依赖赋值给静态成员。这种方法同样需要将工具类设计为非单例模式,或者在每次使用前进行实例化。 ```java public class MyUtils { private static MyDependency myDependency; public static void setMyDependency(MyDependency myDependency) { MyUtils.myDependency = myDependency; } public static void doSomething() { myDependency.performAction(); } } ``` 3. **使用`@PostConstruct`注解**: 通过`@PostConstruct`注解的方法进行依赖注入。这种方法需要在工具类中定义一个非静态的Setter方法,然后在`@PostConstruct`方法中进行赋值。 ```java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyUtils { private static MyDependency myDependency; @Autowired public void setMyDependency(MyDependency myDependency) { MyUtils.myDependency = myDependency; } @PostConstruct public void init() { // 初始化逻辑 } public static void doSomething() { myDependency.performAction(); } } ``` 4. **使用`ApplicationContext`获取Bean**: 在工具类中通过`ApplicationContext`获取依赖的Bean。这种方法需要在工具类中提供一个静态方法,通过`ApplicationContext`获取依赖。 ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class MyUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { MyUtils.applicationContext = applicationContext; } public static void doSomething() { MyDependency myDependency = applicationContext.getBean(MyDependency.class); myDependency.performAction(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值