spring | 通过 @Autowired 向 static 注入
source link: https://benpaodewoniu.github.io/2023/02/01/spring44/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
通过 @Autowired 向 static 注入
姑苏城外一茅屋,万树梅花月满天
最开始我想写
@Service
public class Test{
@Autowired
private static Service1 service1;
private Map<String,Service> serviceMap = new HashMap<>();
static{
serviceMap.put("1",service1);
}
}
最后发现 service1
为 null
。
静态变量、类变量不是对象的属性,而是一个类的属性,所以静态方法是属于类(class
)的,普通方法才是属于实体对象(也就是New
出来的对象)的,spring
注入是在容器中实例化对象,所以不能使用静态方法。
而使用静态变量、类变量扩大了静态方法的使用范围。静态方法在spring
是不推荐使用的,依赖注入的主要目的,是让容器去产生一个对象的实例,然后在整个生命周期中使用他们,同时也让testing
工作更加容易。
一旦你使用静态方法,就不再需要去产生这个类的实例,这会让 testing
变得更加困难,同时你也不能为一个给定的类,依靠注入方式去产生多个具有不同的依赖环境的实例,这种 static field
是隐含共享的,并且是一种 global
全局状态,spring
同样不推荐这样去做。
在Springframework
里,我们是不能@Autowired
一个静态变量,使之成为一个Spring bean
的。为什么?其实很简单,因为当类加载器加载静态变量时,Spring
上下文尚未加载。所以类加载器不会在bean
中正确注入静态类,并且会失败。
- 将
@Autowire
加到构造方法上
@Component
public class Test {
private static UserService userService;
@Autowired
public Test(UserService userService) {
Test.userService = userService;
}
public static void test() {
userService.test();
}
}
- 用
@PostConstruct
注解
@Component
public class Test {
private static UserService userService;
@Autowired
private UserService userService2;
@PostConstruct
public void beforeInit() {
userService = userService2;
}
public static void test() {
userService.test();
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK