springboot autowired无法初始化类,获取NullPointerException

时间:2018-03-07 10:04:12

标签: java spring

使用springboot进行演示,遇到异常: 搜索了两个原因:手动初始化类;没有在类上设置注释。 检查不是这两个问题

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAngularSample1Application {
public static void main(String[] args) {
    SpringApplication.run(SpringBootAngularSample1Application.class, args);
}
}
  1. 控制器用户= userService.saveAll(用户)的异常点; userService为null。
  2. package com.example.demo.geek;

    import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Component;
        import org.springframework.web.bind.annotation.*;
        import java.util.ArrayList;
        import java.util.List;
    
    /**
     * Created by Damith Ganegoda on 9/3/17.
     */
    
    @CrossOrigin(origins = "http://localhost:4200")
    @RestController
    @RequestMapping(value = "/users")
    
    public class UserController {
    
    
    private List<User> users = new ArrayList();
    
    @Autowired
    private UserService userService;
    
    UserController() {
        this.users = buildUsers();
    }
    
    @RequestMapping(method = RequestMethod.GET)
    public List<User> getUsers() {
        return this.users;
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable("id") Long id) {
        return this.users.stream().filter(user -> user.getId() == id).findFirst().orElse(null);
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public User saveUser(@RequestBody User user) {
        Long nextId = 0L;
        if (this.users.size() != 0) {
            User lastUser = this.users.stream().skip(this.users.size() - 1).findFirst().orElse(null);
            nextId = lastUser.getId() + 1;
        }
    
        user = userService.saveUser(user);
        this.users.add(user);
        return user;
    
    }
    
    @RequestMapping(method = RequestMethod.PUT)
    public User updateUser(@RequestBody User user) {
        User modifiedUser = this.users.stream().filter(u -> u.getId() == user.getId()).findFirst().orElse(null);
        modifiedUser.setFirstName(user.getFirstName());
        modifiedUser.setLastName(user.getLastName());
        modifiedUser.setEmail(user.getEmail());
        modifiedUser = userService.saveAndFlush(modifiedUser);
        return modifiedUser;
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public boolean deleteUser(@PathVariable Long id) {
        User deleteUser = this.users.stream().filter(user -> user.getId() == id).findFirst().orElse(null);
        if (deleteUser != null) {
            userService.deleteUser(deleteUser);
            this.users.remove(deleteUser);
            return true;
        } else  {
            return false;
        }
    
    
    }
    
    List<User> buildUsers() {
        List<User> users = new ArrayList<>();
    
        User user1 = buildUser("John", "Doe", "john@email.com");
        User user2 = buildUser("Jon", "Smith", "smith@email.com");
        User user3 = buildUser("Will", "Craig", "will@email.com");
        User user4 = buildUser("Sam", "Lernorad", "sam@email.com");
        User user5 = buildUser("Ross", "Doe", "ross@email.com");
    
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
    
        users = userService.saveAll(users);
    //      userRepo.save(user1);
        return users;
    
    }
    
    User buildUser(String fname, String lname, String email) {
        User user = new User();
    
        user.setFirstName(fname);
        user.setLastName(lname);
        user.setEmail(email);
        return user;
    }
    

    }

    第3。带注释的服务,存储库是自动装配的

    @Service
    public class UserService {
    
        @Autowired
        UserRepository userRepo;
    
        public User saveUser(User user) {
            return userRepo.save(user);
        }
    
        public User saveAndFlush(User user) {
            return userRepo.saveAndFlush(user);
        }
        public List<User> saveAll(List<User> users) {
            return userRepo.saveAll(users);
        }
        public void deleteUser(User user) {
            userRepo.delete(user);
        }
    }
    

    4。存储库

    @Repository
    public interface UserRepository extends JpaRepository<User, String> {
    }
    

    错误消息:

        org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController' defined in file [C:\workstation_bz\workspace\spring-boot-angular-sample-1\target\classes\com\example\demo\geek\UserController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.geek.UserController]: Constructor threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1232) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
        at o
    
    rg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1131) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
            at com.example.demo.SpringBootAngularSample1Application.main(SpringBootAngularSample1Application.java:12) [classes/:na]
        Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.geek.UserController]: Constructor threw exception; nested exception is java.lang.NullPointerException
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:182) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1224) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            ... 17 common frames omitted
        Caused by: java.lang.NullPointerException: null
            at com.example.demo.geek.UserController.buildUsers(UserController.java:90) ~[classes/:na]
            at com.example.demo.geek.UserController.<init>(UserController.java:24) ~[classes/:na]
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_152]
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_152]
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_152]
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_152]
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:170) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
            ... 19 common frames omitted
    

2 个答案:

答案 0 :(得分:1)

此代码在您的控制器中存在问题。在UserController对象实例化之前,您正在尝试使用userService对象。

UserController() {
    this.users = buildUsers();
}

而是在控制器中实现InitializingBean,并在afterPropertiesSet()方法中调用buildUsers()方法。在实例化对象od UserController类之后调用afterPropertiesSet()方法 @override

public void afterPropertiesSet() throws Exception {
    // TODO Auto-generated method stub
}

答案 1 :(得分:0)

在调用buildUsers()之前,您应该使用构造函数注入而不是UserService的字段注入来确保它是实例化的:

在UserController中:

private final UserService userService;

UserController(UserService userService) {
    this.userService = userService;
    this.users = buildUsers();
}

这将阻止它在行

处的空指针
users = userService.saveAll(users)