Spring静态注入

目录

需求:在静态方法中注入并使用Spring管理下的bean。

解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import javax.annotation.PostConstruct;

public class DemoUtil {
private static DemoUtil demoUtil;
@Autowire
public DemoServ demoServ;//需注入的对象

/**
* 构造方法执行后调用 init()
*/
@PostConstruct
public void init() {
demoUtil = this;
demoUtil.demoServ = this.demoServ;
}

public static void utilMethod() {
demoUtil.demoServ.method1();
}
}