您可以通过以下解决方案之一来实现此目的:
使用构造函数@Autowired
这种方法将构造需要一些bean作为构造函数参数的bean。在构造函数代码中,设置静态字段的值为参数为构造函数执行。样品:
@Component
public class Boo {
private static Foo foo;
@Autowired
public Boo(Foo foo) {
Boo.foo = foo;
}
public static void randomMethod() {
foo.doStuff();
}
}
使用@PostConstruct将值移交给静态字段
这里的想法是在bean由spring配置之后将bean移交给静态字段。
@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();
}
}