Spring Bean类可以包含静态方法吗?
I hope this isn't too noob of a question, I'm still quite new to Spring. Can a bean class contain static methods? My initial thoughts is no because a static method is global, there's one instance per the entire application and threads to share but a bean might not be defined as such.
我希望这不是一个问题的太多菜鸟,我对Spring来说还是一个新手。 bean类可以包含静态方法吗?我最初的想法是否定的,因为静态方法是全局的,每个应用程序和共享的线程都有一个实例,但bean可能没有这样定义。
I tried searching for this question but couldn't find a clear answer.
我试着寻找这个问题,但找不到明确的答案。
2 个解决方案
#1
1
Yes,
A spring bean may have static methods too.
spring bean也可能有静态方法。
Using constructor @Autowired
使用构造函数@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;
}
}
You may also do it this way: Using @PostConstruct to hand value over to static field
您也可以这样做:使用@PostConstruct将值传递给静态字段
The idea here is to hand over a bean to a static field after bean is configured by spring.
这里的想法是在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();
}
}
source: @Autowired and static method
来源:@Autowired和静态方法
更多相关文章
- Java读取Unicode文件(UTF-8等)时碰到的BOM首字符问题,及处理方法
- java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
- java 和 JavaScript都可以在创建一个对象时,就可以通过这个对象调
- 有什么方法可以避免HibernateOptimisticLockingFailureException
- native方法的使用
- Java Quartz的使用方法,实现程序计时
- 将行计数器方法与字数统计方法相结合
- java基础:集合框架之Map(共性方法)
- JAVA中的反射只获取属性的get方法