java - 如何在Comparator類中autowire一個(gè)接口
問題描述
使用springboot,和mongo的repository,我定義了一個(gè)Comparator類,想實(shí)現(xiàn)自己的對象的比較方法。代碼如下:
package com.story.utils;import java.util.Comparator;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.story.model.Phase;import com.story.model.Story;import com.story.repository.StoryRepository;@Servicepublic class PhaseComparator implements Comparator<Phase>{private String field;private Story story;@Autowired private StoryRepository storyRepository; public PhaseComparator() {super(); } public PhaseComparator (String field) {this.field = field; } @Override public int compare(Phase phase_1, Phase phase_2) {if (this.field.equals('createdDate')) { return phase_1.getCreatedDate() < phase_2.getCreatedDate() ? -1 : 1;} else { Story foundStory_1 = this.storyRepository.findOne(phase_1.getStoryId()); Story foundStory_2 = this.storyRepository.findOne(phase_1.getStoryId()); return foundStory_1.getLastUpdatedDate() < foundStory_2.getLastUpdatedDate() ? -1 : 1;} }}
但是,這樣的話,storyRepository就是null。請問應(yīng)該如何處理呢?謝謝
問題解答
回答1:這樣寫應(yīng)該沒問題,但是你用的時(shí)候必須從 Spring 上下文中去取,比如用 @Autowired 。不知道你是不是這么做的。如果你用的時(shí)候臨時(shí)再去 new PhaseComparator() ,那里面的 storyRepository 肯定是 null。
相關(guān)文章:
1. python - 《flask web 開發(fā)》一書,數(shù)據(jù)庫中多對多關(guān)系的實(shí)現(xiàn)問題?2. 關(guān)于phpstudy設(shè)置主從數(shù)據(jù)庫3. mysql - 我用SQL語句 更新 行的時(shí)候,發(fā)現(xiàn)全部 中文都被清空了,請問怎么解決?4. centos7 編譯安裝 Python 3.5.1 失敗5. python3.x - python3.5使用pyinstaller打包報(bào)錯(cuò)找不到libpython3.5mu.so.1.0等文件求解?6. phpStudy2017輕巧版mysql無法啟動(dòng)7. 為什么我輸入了refresh不會(huì)跳轉(zhuǎn)?請教大神支招!8. 為什么顯示數(shù)據(jù)丟失呢9. 為什么我寫的PHP不行10. MySQL在什么情況下會(huì)被堵死?
