Ber*_*kin 1 java repository autowired spring-boot
我正在尝试在名为CacheManager的类中使用存储库。这个存储库应该从表中获取所有行。尽管使用了@Autowired 注释,它还是为空。我在哪里失踪?谢谢。
@Repository
public interface FraudCacheListRepository extends CrudRepository<FraudCacheListEntity,Integer> {
List<FraudCacheListEntity> findAll();
}
Run Code Online (Sandbox Code Playgroud)
@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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
@Component
@Configurable
public class CoreController {
public ComController com;
@Autowired
private CacheManager cacheManager;
public CoreController() {
com = new ComController();
}
}
Run Code Online (Sandbox Code Playgroud)
@RestController
public class FraudRestController {
@Autowired
private CoreController core;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
由于您使用了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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
它对您不起作用的原因是在注入发生之前调用了构造函数。该@PostConstruct注解指示 Spring在 bean 完全初始化后调用getAllTables方法。
| 归档时间: |
|
| 查看次数: |
5221 次 |
| 最近记录: |