spring - 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 新手,请用示例代码解释您的解决方案。
解决方案
您必须以这种方式更改代码:
如果要在类的构造函数中使用自动装配的 bean,请使用构造函数注入。这也是最推荐的注射方式。
@Component
public class StoreWorker {
private final StoreRepository storeRepository;
public StoreWorker(StoreRepository storeRepository) {
this.storeRepository = storeRepository;
System.out.println(storeRepository.findAll());
}
}
因此,当StoreWorker
实例化时,自动装配的 beanstoreRepository
会被注入。由于发生这种情况,您可以使用storeRepository
bean。
推荐阅读
- linux - 用于多个图像的 ImageMagick V7 和修剪工具
- node.js - 如何使用其 web api 将 FIT 文件上传到 Google FIT?
- c# - 统一创建android项目时出错
- mustache - 总是错误 - “路径”参数必须是字符串、缓冲区或 URL 类型之一。接收类型未定义
- javascript - 如果一个新的 Promise 在外部函数内部 .then() .catch() 添加在哪里?
- javascript - 基于外部变量将信息块推送到数组 X 次
- python - 如何加快稀疏矩阵之间的方差计算
- next.js - 如果进程名称相同,PM2 是否有启动新进程或重新启动现有进程的命令?
- html - 身高没有改变/在我的网站上工作
- php - 将数据从视图传递到控制器,其中数据来自另一个控制器