How to autowire an interface in Comparator class
大家讲道理
大家讲道理 2017-06-28 09:24:59
0
1
933

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
大家讲道理

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!