@Autowired 和静态方法 [英] @Autowired and static method
问题描述
我有 @Autowired
服务,它必须在静态方法中使用.我知道这是错误的,但我不能改变当前的设计,因为它需要大量的工作,所以我需要一些简单的技巧.我不能将 randomMethod()
更改为非静态的,我需要使用这个自动装配的 bean.任何线索如何做到这一点?
I have @Autowired
service which has to be used from within a static method. I know this is wrong but I cannot change the current design as it would require a lot of work, so I need some simple hack for that. I can't change randomMethod()
to be non-static and I need to use this autowired bean. Any clues how to do that?
@Service
public class Foo {
public int doStuff() {
return 1;
}
}
public class Boo {
@Autowired
Foo foo;
public static void randomMethod() {
foo.doStuff();
}
}
推荐答案
您可以按照以下解决方案之一进行操作:
You can do this by following one of the solutions:
这种方法将构造需要一些 bean 作为构造函数参数的 bean.在构造函数代码中,您使用作为构造函数执行参数的值设置静态字段.示例:
This approach will construct the bean requiring some beans as constructor parameters. Within the constructor code you set the static field with the value got as parameter for constructor execution. Sample:
@Component
public class Boo {
private static Foo foo;
@Autowired
public Boo(Foo foo) {
Boo.foo = foo;
}
public static void randomMethod() {
foo.doStuff();
}
}
使用@PostConstruct 将值交给静态字段
这里的思路是在spring配置好bean后,将bean交给静态字段.
Using @PostConstruct to hand value over to static field
The idea here is to hand over a bean to a static field after bean is configured by spring.
@Component
public class Boo {
private static Foo foo;
@Autowired
private Foo tFoo;
@PostConstruct
public void init() {
Boo.foo = tFoo;
}
public static void randomMethod() {
foo.doStuff();
}
}
这篇关于@Autowired 和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!