gpt4 book ai didi

spring - 如何在带有接线的 Spring Boot 应用程序中运行特定的类/实用程序?

转载 作者:行者123 更新时间:2023-12-03 03:58:11 24 4
gpt4 key购买 nike

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

我可以使用 gradlew 运行任意类;

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

然而,当以这种方式运行时,“ Autowiring ”都不起作用。执行任意类(具有 main 方法)以使其也适用于任何 Autowiring 的更好方法是什么?

编辑:

我得到了一些使用 CommandLineRunner 和一些参数的建议,它们可以通过以下方式执行命令:
./gradlew bootRun -Pargs=--reloadTestData

但是,我的 repo 的 Autowiring 失败了。我所拥有的是:
@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 始终为空,即使我在我的“常规” Spring 启动应用程序中以相同的方式连接也没有问题。我需要做什么才能正确接线?

最佳答案

您说要运行“作业”这一事实表明您可能希望在应用程序中使用计划任务,而不是尝试通过命令行运行它。例如Scheduling tasks in Spring

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

如果你想让一个命令行应用程序使用 Autowiring ,你可以通过让你的 Application 类实现 CommandLineRunner 来创建一个命令行应用程序。接口(interface),例如 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到属性文件。

关于spring - 如何在带有接线的 Spring Boot 应用程序中运行特定的类/实用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52778546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com