我创建了一个 Spring 启动项目。
我使用 Elasticsearch 的 Spring 数据。
整个管道: Controller -> 服务 -> 存储库已准备就绪。
我现在有一个代表国家对象(名称和 isoCode)的文件,我想创建一个作业以将它们全部插入 Elasticsearch 中。
我阅读了 spring 文档,发现对于这样一个简单的工作来说配置太多了。
所以我正在尝试做一个简单的主要“工作”,它读取 csv、创建对象并将它们插入 Elasticsearch 中。
但是我很难理解在这种情况下注入(inject)是如何工作的:
@Component
public class InsertCountriesJob {
private static final String file = "D:path\\to\\countries.dat";
private static final Logger LOG = LoggerFactory.getLogger(InsertCountriesJob.class);
@Autowired
public CountryService service;
public static void main(String[] args) {
LOG.info("Starting insert countries job");
try {
saveCountries();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveCountries() throws Exception {
try (CSVReader csvReader = new CSVReader(new FileReader(file))) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
String name = values[0];
String iso = values[1].equals("N") ? values[2] : values[1];
Country country = new Country(iso, name);
LOG.info("info: country: {}", country);
//write in db;
//service.save(country); <= can't do this because of the injection
}
}
}
}
最佳答案
根据西蒙的评论。这是我解决问题的方法。可能会帮助那些正在进入 Spring 并且努力不迷路的人。
基本上,要在 Spring 中注入(inject)任何东西,你需要一个 SpringBootApplication
public class InsertCountriesJob implements CommandLineRunner{
private static final String file = "D:path\\to\\countries.dat";
private static final Logger LOG = LoggerFactory.getLogger(InsertCountriesJob.class);
@Autowired
public CountryService service;
public static void main(String[] args) {
LOG.info("STARTING THE APPLICATION");
SpringApplication.run(InsertCountriesJob.class, args);
LOG.info("APPLICATION FINISHED");
}
@Override
public void run(String... args) throws Exception {
LOG.info("Starting insert countries job");
try {
saveCountry();
} catch (Exception e) {
e.printStackTrace();
}
LOG.info("job over");
}
public void saveCountry() throws Exception {
try (CSVReader csvReader = new CSVReader(new FileReader(file))) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
String name = values[0];
String iso = values[1].equals("N") ? values[2] : values[1];
Country country = new Country(iso, name);
LOG.info("info: country: {}", country);
//write in db;
service.save(country);
}
}
}
}
关于java - 创建一个简单的工作spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159144/