1.问题描述
今天在写接口时,遇到这样一个问题:
原本在service正常的去注入我所需要的类:
但是我在某个静态方法中,需要用
我们知道,在静态方法中,静态方法只能访问静态变量和调用静态方法。这是由于静态方法和静态变量是属于类而不是属于类的实例。
所以把这里改为了静态
此时在用这里调用时,报空指针了:
于是:我把这两个static都去掉了,解决了,因为这个方法我并不是一定要static的。
但是产生了一个问题:为什么SpringBoot注入不了静态变量和属性呢?
答:静态变量和方法属于类级别,而 Spring 的依赖注入默认是基于实例级别的。这意味着 Spring 容器不能直接注入静态成员变量,因为静态成员变量在类加载时就已经存在,并且生命周期不同于 Spring 管理的 Bean 实例。
那假如我们想强行注入呢。
同样,也是有方法的:
1.最常用的
通过 @Autowired 的 setter 方法
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
private static SomeDependency someDependency;
@Autowired
public void setSomeDependency(SomeDependency someDependency) {
MyService.someDependency = someDependency;
}
public static void doSomething() {
someDependency.performAction();
}
}
2.使用 @PostConstruct
你可以使用 @PostConstruct 注解来设置静态属性,利用实例变量的注入来给静态变量赋值。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class MyService {
@Autowired
private SomeDependency someDependency;
private static SomeDependency staticSomeDependency;
@PostConstruct
public void init() {
MyService.staticSomeDependency = this.someDependency;
}
public static void doSomething() {
staticSomeDependency.performAction();
}
}
总结:实际上我们很少在Service去给他注入静态变量,我们更多的可能在工具类中才会出现此场景,一般是不建议的