首页 > 解决方案 > Spring Boot:如何访问java类@Autowired中的存储库不起作用

问题描述

Spring Boot:如何访问java类@Autowired中的存储库不起作用

由于我是 Spring Boot 新手,请用示例代码解释您的解决方案。

存储库

import java.util.List;
import org.springframework.data.repository.CrudRepository;

public interface StoreRepository extends CrudRepository<Store, Integer> {

    List<Store> findAll();
}

实体店

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Store {

    @Id
    private Integer sid;
    private String sname;


    public Store() {

    }

    public Store(Integer sid, String sname) {
        super();
        this.sid = sid;
        this.sname = sname;

    }

///GETTER and Setters   here...

}

**门店服务**

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class StoreService {

    @Autowired
    private StoreRepository storeRepository;

    public StoreService() {

    }

    public List<Stores> getAllStores(){
        return (List<Stores>) storeRepository.findAll(); /* This works good. Through controller I can retrieve all data*/

    }

}

简单的 Java 类

@Component
public class StoreWorker {

    @Autowired
    private StoreRepository storeRepository;

    public StoreWorker() {

        System.out.println(storeRepository.findAll()); /* Error */

    }

错误 :

Exception in thread "StoreWorker : restartedMain" java.lang.reflect.InvocationTargetException
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.store.workers.StoreWorker]: Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException

由于我是 Spring Boot 新手,请用示例代码解释您的解决方案。

标签: springspring-bootspring-data-jpa

解决方案


您必须以这种方式更改代码:

如果要在类的构造函数中使用自动装配的 bean,请使用构造函数注入。这也是最推荐的注射方式。

@Component
public class StoreWorker {

    private final StoreRepository storeRepository;

    public StoreWorker(StoreRepository storeRepository) {
        this.storeRepository = storeRepository;
        System.out.println(storeRepository.findAll());
    }
}

因此,当StoreWorker实例化时,自动装配的 beanstoreRepository会被注入。由于发生这种情况,您可以使用storeRepositorybean。


推荐阅读