我正在尝试在名为 CacheManager 的类中使用存储库。该存储库应从表中获取所有行。尽管使用@Autowired批注,但它仍为null。我在哪里想念?谢谢。
@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();
}
}
@RestController
public class FraudRestController {
@Autowired
private CoreController core;
}
答案 0 :(得分:3)
由于使用了private CoreController core = new CoreController();
,因此CoreController和CacheManager不是Spring托管的bean,因此不会发生依赖项注入。
更新
我建议您采用这种方法:
@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;
@PostConstruct
public void getAllTables(){
List<FraudCacheListEntity> fraudCacheListEntities = fraudCacheListRepository.findAll();
for (FraudCacheListEntity entity:fraudCacheListEntities) {
System.out.println(entity.toString());
}
}
}
它对您不起作用的原因是在注入发生之前调用了构造函数。 @PostConstruct
注释指示Spring在完全初始化Bean后调用getAllTables
方法。