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

 

posted on 2019-04-23 17:56  liehen2046  阅读(1132)  评论(0编辑  收藏  举报