下面是我的SourceRepository类,它不覆盖自动生成的返回Iterable的通用findAll(
package com.infostream.repositories;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.infostream.models.Source;
public interface SourceRepositoryImpl extends PagingAndSortingRepository<Source, Long>{
Page<Source> findAll(Pageable pageRequest);
}
下面是我的服务类:
package com.infostream.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import com.infostream.models.Source;
import com.infostream.repositories.SourceRepositoryImpl;
@Component
public class SourcesService {
@Autowired
private SourceRepositoryImpl sourceRepository;
public PageImpl<Source> getPaginatedSources(Pageable pageRequest) {
Page<Source> searchResultPage = sourceRepository.findAll(pageRequest);
return new PageImpl<Source>(searchResultPage.getContent(), pageRequest, searchResultPage.getTotalElements());
}
public Iterable<Source> getAllSources() {
return sourceRepository.findAll();
}
}
这是我的主类,我将它作为Java应用程序运行。
package com.infostream.services;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.infostream.consumers.RssArticleConsumer;
import com.infostream.models.Article;
import com.infostream.models.Source;
import com.infostream.producers.RssXmlProducer;
public class HarvestService {
private static BlockingQueue<Article> article_queue = new ArrayBlockingQueue<Article>(10);
@Autowired
private static SourcesService sourcesService;
public static void main(String[] args) throws InterruptedException {
Iterable<Source> sources = sourcesService.getAllSources();
/*
for(Source s : sources) {
System.out.println(s.getUrl());
}
Thread t1 = new Thread(new RssXmlProducer(sources.iterator().next(), article_queue));
Thread t2 = new Thread(new RssArticleConsumer(article_queue));
t1.start();
t2.start();
t1.join();
t2.join();
*/
}
}
sourcesService变量为空,我看到自动安装不起作用,但我不知道为什么。这是因为我在包资源管理器中右键单击HarvestService文件并单击作为Java应用程序运行,将其作为Java应用程序运行吗?
4条答案
按热度按时间v440hwme1#
我也遇到了同样的问题,
@Autowired
在主类中不工作,我所做的是获取对ApplicationContext
的引用,然后使用它将sourcesService
作为bean获取我已经重写了你的类如下
k5hmc34c2#
你使用的是 Spring Boot 吗?看起来你的HarvestService类需要
@SpringBootApplication
,并将其添加到主函数中并确保您在Maven/Gradle中有正确的依赖关系。希望这对您有帮助
wvt8vs2t3#
您必须实现CommandLineRunner并将代码放入方法run中,因为spring需要加载所有组件,而使用普通main将无法正常工作
SpringApplication.run main method
ercv8c1e4#
使用了modelmapper依赖项(2.4.4)。使用@RequiredArgsConstructor和modelmapper方法,在主类上带有@Bean注解。要初始化的bean应该是final。