Accessing Application Arguments
If you need to access the application arguments that were passed to SpringApplication.run(…)
, you can inject a org.springframework.boot.ApplicationArguments
bean. The ApplicationArguments
interface provides access to both the raw String[]
arguments as well as parsed option
and non-option
arguments, as shown in the following example:
1 | import java.util.List; |
Spring Boot also registers a
CommandLinePropertySource
with the SpringEnvironment
. This lets you also inject
single application arguments by using the@Value
annotation.
Using the ApplicationRunner or CommandLineRunner
If you need to run some specific code once the
SpringApplication
has started, you can implement the
ApplicationRunner
orCommandLineRunner
interfaces. Both interfaces work in the same way and offer a singlerun
method, which is called just beforeSpringApplication.run(…)
completes.
The CommandLineRunner
interfaces provides access to application arguments as a string array, whereas the ApplicationRunner
uses the ApplicationArguments
interface discussed earlier. The following example shows a CommandLineRunner
with a run
method:
1 | import org.springframework.boot.CommandLineRunner; |
If several CommandLineRunner
or ApplicationRunner
beans are defined that must be called in a specific order, you can additionally implement the org.springframework.core.Ordered
interface or use the org.springframework.core.annotation.Order
annotation.
Application Exit
Each SpringApplication
registers a shutdown hook with the JVM to ensure that the ApplicationContext
closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean
interface or the @PreDestroy
annotation) can be used.
In addition, beans may implement the org.springframework.boot.ExitCodeGenerator
interface if they wish to return a specific exit code when SpringApplication.exit()
is called. This exit code can then be passed to System.exit()
to return it as a status code, as shown in the following example:
1 | import org.springframework.boot.ExitCodeGenerator; |
Also, the ExitCodeGenerator
interface may be implemented by exceptions. When such an exception is encountered, Spring Boot returns the exit code provided by the implemented getExitCode()
method.
欢迎关注我的公众号 须弥零一,跟我一起学习IT知识。
如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !