【发布时间】:2019-04-06 19:27:05
【问题描述】:
我正在尝试在名为 CacheManager 的类中使用存储库。此存储库应从表中获取所有行。尽管使用了@Autowired 注释,它还是为空。我在哪里失踪?谢谢。
存储库
@Repository
public interface FraudCacheListRepository extends CrudRepository<FraudCacheListEntity,Integer> {
List<FraudCacheListEntity> findAll();
}
缓存管理器
@Component
public class CacheManager {
private long second = 1000L;
private long minute = second * 60;
private long hour = minute * 60;
private long TTL = hour;
@Autowired
private FraudCacheListRepository fraudCacheListRepository;
public CacheManager() {
getAllTables();
}
private void getAllTables(){
List<FraudCacheListEntity> fraudCacheListEntities = fraudCacheListRepository.findAll();
for (FraudCacheListEntity entity:fraudCacheListEntities) {
System.out.println(entity.toString());
}
}
}
核心控制器
@Component
@Configurable
public class CoreController {
public ComController com;
@Autowired
private CacheManager cacheManager;
public CoreController() {
com = new ComController();
}
}
MAIN - 休息控制器
@RestController
public class FraudRestController {
@Autowired
private CoreController core;
}
【问题讨论】:
-
请记住,字段注入发生在构造函数完全执行之后。所以
CacheManager.getAllTables()将产生NullPointerException,因为字段fraudCacheListRepository没有初始化。建议:由字段注入改为构造函数注入。 -
我改了代码但问题依然存在
-
在构造函数中:public CacheManager() { getAllTables();这将在存储库依赖之前作为依赖注入。修复您需要创建 @PostConstructor private void init() { getAllTables();如果可行,请在构造函数中将其删除,否则请投票有用,否则请告诉我。亲切的问候
标签: java spring-boot repository autowired