某些業(yè)務場景需要我們將方法定義成靜態(tài)方法样眠,該靜態(tài)方法還依賴別的被容器管理的類
@Service
public class Foo {
public int doStuff() {
System.out.println("hehe");
return 1;
}
}
@Component
public class Boo {
@Autowired
private static Foo foo;
public static void test() {
foo.doStuff();
}
}
這樣必然報java.lang.NullPointerException: null
異常纠吴,解決辦法:
1.將@Autowire加到構造方法上
@Component
public class Boo {
private static Foo foo;
@Autowired
public Boo(Foo foo) {
Boo.foo = foo;
}
}
2.用@PostConstruct注解
@Component
public class Boo {
private static Foo foo;
@Autowired
private Foo foo2;
@PostConstruct
public void beforeInit() {
foo = foo2;
}
public static void test() {
foo.doStuff();
}
}