首页 > 解决方案 > 存储库未使用 @Autowired 实例化

问题描述

我有一个 JPA 存储库的空指针异常,我认为存储库在具有@Autowired.

@Component
public class UserService {

    @Autowired
    UserRepository repository;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void createUser(User user) {
        System.out.println("user email = " + user.getEmail());
        repository.save(user);
    }
...

应用

@ComponentScan({"mypackage", "mypackage.service"})
@SpringBootApplication
public class Application implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
    }
}

标签: javahibernatespring-data-jpa

解决方案


@autowired 用于注入由 spring 容器基于 applicationcontext.xml 文件预先实例化的 bean,因此请确保在该文件中添加您想要注入的适当 bean。 来自春天的文档


推荐阅读