创建一个简单的作业 spring boot

Create a simple job spring boot

我创建了一个 spring 引导项目。 我在弹性搜索中使用 spring 数据。 整个管道:控制器 -> 服务 -> 存储库已准备就绪。

我现在有一个代表国家/地区对象(名称和 isoCode)的文件,我想创建一个作业以将它们全部插入弹性搜索中。 我阅读了 spring 文档,发现对于这样一个简单的工作来说配置太多了。 所以我正在尝试做一个简单的 main "job" 来读取 csv,创建对象并将它们插入到弹性搜索中。

但是我很难理解注入在这种情况下是如何工作的:

@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 中注入任何内容,您需要一个 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);
        }
    }
}


}