如何将repo注入实用程序类?自动连线不工作

utugiqy6  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(251)

我需要一些帮助来解决我的问题。我创建了一个实用类,并在这里注入了一些crudepositories。但是这里的寄宿地不太好用。它们返回nullpointerexception(存储库只能在控制器中正常工作)。下面是错误和一些代码。错误图像
我再次注意到,控制器中不会出现此类错误。

@Repository
public interface EventRepository extends CrudRepository<Event, Long> {

    @Query(nativeQuery = true, value = "select * from events e order by e.id desc LIMIT 5")
    List<Event> getEventsWithLimit();

}
@Service
public class CachedObject extends TimerTask {

    @Autowired
    EventRepository eventRepository;
    @Autowired
    MatchRepository matchRepository;
    @Autowired
    PlayerRepository playerRepository;
    @Autowired
    ImageRepository imageRepository;

    List<Rank> ranking;

    List<Image> image;

    //Last 10 next Matches
    List<Match> nextMatches;

    //Last 10 results
    List<Match> results;

    List<PlayerOfTheWeek> playerOfTheWeek;

    //Last 5 event
    List<Event> events;

    @Override
    public void run() {
        try{
            refreshCache();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void refreshCache() throws Exception{

        events = eventRepository.getEventsWithLimit();
        image = imageRepository.getRandomImage();
        results = matchRepository.getLastResult();
        nextMatches = matchRepository.getLastMatches();
        ranking = makeRanking();
        ...
    }
    ...
}

你能给我一些找解决方案的建议吗((

ego6inou

ego6inou1#

如果您想使用解决方案timertask,我认为您需要使用所需的自动连接bean创建一个构造函数。但spring中更好的解决方案是使用@scheduler注解定期执行所需的方法(更多关于 Spring 调度程序的信息https://spring.io/guides/gs/scheduling-tasks/)

相关问题