在下拉向导应用程序中, 在主服务中,通常使用如下内容覆盖Application类中的抽象Run方法:
@Override
public void run(MyServiceConfiguration configuration, Environment environment) throws Exception {
// application logic
}
我try 跟踪执行逻辑,但无法弄清楚该方法是在哪里调用的,或者是如何调用的.有谁能给我指个方向吗?
在下拉向导应用程序中, 在主服务中,通常使用如下内容覆盖Application类中的抽象Run方法:
@Override
public void run(MyServiceConfiguration configuration, Environment environment) throws Exception {
// application logic
}
我try 跟踪执行逻辑,但无法弄清楚该方法是在哪里调用的,或者是如何调用的.有谁能给我指个方向吗?
让我们从头开始,当您运行Dropwizard application as a server时,您在命令行界面(CLI)上给出了server
命令.
文档给出的示例如下:
JAVA-JAR目标/Hello-world-0.0.1-SNAPSHOT.jar服务器Hello-world.yml
在io.dropwizard.Application
(您通常会对其进行扩展)中,我们可以看到bootstrap
中添加了以下命令:
protected void addDefaultCommands(Bootstrap<T> bootstrap) {
bootstrap.addCommand(new ServerCommand<>(this));
bootstrap.addCommand(new CheckCommand<>(this));
}
在本例中,this
是您的类扩展Application
的实例,它被提供给ServerCommand
.
然后,同一类中的run
方法将解析CLI:
public void run(String... arguments) throws Exception {
final Bootstrap<T> bootstrap = new Bootstrap<>(this);
addDefaultCommands(bootstrap);
initialize(bootstrap);
// Should be called after initialize to give an opportunity to set a custom metric registry
bootstrap.registerMetrics();
final Cli cli = new Cli(new JarLocation(getClass()), bootstrap, System.out, System.err);
// only exit if there's an error running the command
cli.run(arguments).ifPresent(this::onFatalError);
}
当我们跟随 cli.run(arguments).ifPresent(this::onFatalError);
的时候,我们最终得到了io.dropwizard.cli.Cli#run
.在此方法中,命令被解析,由于我们指定了server
,因此它将通过名称找到该命令并执行它:
public Optional<Throwable> run(String... arguments) {
...
final Namespace namespace = parser.parseArgs(arguments);
final Command command = requireNonNull(commands.get(namespace.getString(COMMAND_NAME_ATTR)),
"Command is not found");
try {
command.run(bootstrap, namespace);
...
服务器命令将是io.dropwizard.cli.ServerCommand
的一个实例,它扩展了io.dropwizard.cli.EnvironmentCommand
.
在EnvironmentCommand
中,我们可以看到您所请求的Application.run(...)
方法已执行:
protected void run(Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
...
bootstrap.run(configuration, environment);
Application.run(配置、环境);
run(environment, namespace, configuration);
}
这一行具体如下:
Application.run(配置、环境);
T configuration
是通过基类EnvironmentCommand
相加的,基类是io.dropwizard.cli.ConfiguredCommand
.
所有代码均取自Drop向导版本2.1.0