Instantiation of bean failed;nested exception is org.springframework.beans.BeanInstantiationExcept:

但我们在构造函数里使用通过@Autowired注释去bean的一个服务时,出现NullPointerException,也就是空指针异常
Instantiation of bean failed;nested exception is org.springframework.beans.BeanInstantiationExcept:Constructor threw exception; nested exception is java.lang.NullPointerException
出错代码如下

public class ServiceImpl {
    
    
    @Autowired
    private UserService userService;
    
    public ServiceImpl() {
    
    
        userService.findAll();
    }
}

事实上,我们使用Spring@Autowired注解时,实例化函数往往在bean之前,此时使用ServiceImpl时userService还没实例化,所以会出现空指针异常。

此时我们只需要把@Autowired写到构造函数处this.userService = userService;去实例化userService,就可以了,再由外面的@Autowired创建Bean实例。

public class ServiceImpl {
    
    
    
    private UserService userService;
    
    @Autowired
    public ServiceImpl(UserService userService) {
    
    
    	this.userService = userService;
        userService.findAll();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42783654/article/details/108622930