如何在带有布线的 Spring 引导应用程序中运行特定的类/实用程序?



我有我的标准 Spring Boot 应用程序在工作。 我有想要运行"作业"的情况,它基本上是一些特定的方法,通常通过用户在浏览器中执行某些操作来运行,但我想从命令行运行它。

我能够使用 gradlew 运行任意类;

./gradlew -PmainClass=kcentral.backingservices.URLMetaExtractor execute

但是,当以这种方式运行时,没有任何"自动布线"工作。 执行任意类(具有main方法(以便它也适用于任何自动连线的更好方法是什么?

编辑:

我得到了一些使用CommandLineRunner和一些args的建议,它们通过以下方式执行命令:

./gradlew bootRun -Pargs=--reloadTestData

但是,我的存储库的自动布线失败。 我拥有的是:

@EnableAutoConfiguration
@EnableMongoAuditing
@EnableMongoRepositories(basePackageClasses=KCItemRepo.class)
@ComponentScan(basePackages = {"kcentral"})
public class ReloadTestData implements CommandLineRunner {
@Autowired
AddItemService addItemService;
@Autowired
KCItemRepo itemRepo;
@Autowired
KCItemRatingRepo itemRatingRepo;

private static final Logger log = LoggerFactory.getLogger(ReloadTestData.class);

public void reloadData(){
log.info("reloadData and called");
if (itemRepo == null){
log.error("Repo not found");
return;
}
long c = itemRepo.count();
log.warn("REMOVING ALL items "+c);
itemRepo.deleteAll();
log.warn("REMOVING ALL ratings");
itemRatingRepo.deleteAll();
}

itemRepo 始终为空,即使我在"常规"春季启动应用程序中以相同的方式连接而没有问题。 我需要做什么才能正确接线?

您说要运行"作业"这一事实表明您可能希望在应用程序中使用计划任务,而不是尝试通过命令行运行它。 例如,在春季调度任务

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}

如果你想让命令行应用程序与自动连线一起工作,你可以通过让你的应用程序类实现CommandLineRunner接口来创建一个命令行应用程序,例如 Spring Boot Console App

@SpringBootApplication
public class SpringBootConsoleApplication 
implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
@Override
public void run(String... args) {
}
}

并将spring.main.web-application-type=NONE添加到属性文件中。

如果要在运行后停止应用程序,可以使用SpringApplication.exit(ctx)。不过不知道您的自动布线问题,也许可以尝试打印出可用 bean 的列表,这可能会提供一些见解。例:

@Component
public class DoThenQuit implements CommandLineRunner {
@Autowired
private ApplicationContext ctx;
@Override
public void run(String[] args) {
// do some other stuff before quitting
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.stream(beanNames).forEach(System.out::println);

// then quit the application
SpringApplication.exit(ctx);
}
}

最新更新