我希望这不是一个太菜鸟的问题,我对 Spring 还很陌生。 bean 类可以包含静态方法吗?我最初的想法是否定的,因为静态方法是全局的,每个整个应用程序和线程都有一个实例可以共享,但 bean 可能不会这样定义。
我尝试搜索这个问题,但找不到明确的答案。
最佳答案
是的,
Spring bean 也可能有静态方法。
使用构造函数@Autowired
@Component
public class Boo {
private static Foo foo;
@Autowired
public Boo(Foo foo) {
Boo.foo = foo;
}
public static void randomMethod() {
foo.doStuff();
}
public static int getThree(){
return 3;
}
}
你也可以这样做: 使用@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 - Spring Bean 类可以包含静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706523/