Using springboot and mongo's repository, I defined a Comparator class and wanted to implement the comparison method of my own objects. code show as below:
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;
@Service
public 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;
}
}
}
But, in this case, storyRepository is null.
How should we deal with it?
Thanks
大家讲道理2017-06-28 09:26:59
Writing like this should be fine, but you must get it from the Spring context when using it, such as using @Autowired
. I don't know if that's what you did. If you temporarily use new PhaseComparator()
when using it, the storyRepository
inside will definitely be null.