自动连线资料库为空

时间:2018-11-02 14:30:21

标签: java spring-boot repository autowired

我正在尝试在名为 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;
}

1 个答案:

答案 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方法。