我有 @Autowired
服务,它必须在静态方法中使用。我知道这是错误的,但我无法更改当前的设计,因为它需要大量的工作,所以我需要一些简单的技巧。我无法将 randomMethod()
更改为非静态的,我需要使用这个 Autowiring 的 bean。任何线索如何做到这一点?
@Service
public class Foo {
public int doStuff() {
return 1;
}
}
public class Boo {
@Autowired
Foo foo;
public static void randomMethod() {
foo.doStuff();
}
}
最佳答案
您可以通过以下解决方案之一来做到这一点:
使用构造函数@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 将值传递给静态字段
这里的思路是在spring配置bean之后,将一个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();
}
}
关于java - @Autowired 和静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17659875/