@Autowired注解和静态方法

时间:2021-07-21 15:47:13

@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;
}
}