@Autowired注解入static属性时,出现NullPointerException异常。
使用构造方法可解决:
@Component
public class Test { private static UserService userService; @Autowired
public Test(UserService userService) {
Test.userService = userService;
} public static void test() {
userService.test();
}
}
使用@PostConstruct注解解决:
@Component
public class Test { private static UserService userService; @Autowired
private UserService userServiceAdd; @PostConstruct
public void beforeInit() {
userService = userServiceAdd;
}
}