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

 

相关文章:

  • 2021-08-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2022-01-13
猜你喜欢
  • 2022-01-08
  • 2021-06-06
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
相关资源
相似解决方案