目录
71.5 Create a non-web application
官方文档
71.5 Create a non-web application
Not all Spring applications have to be web applications (or web services). If you want to execute some code in a
main
method, but also bootstrap a Spring application to set up the infrastructure to use, then it’s easy with theSpringApplication
features of Spring Boot. ASpringApplication
changes itsApplicationContext
class depending on whether it thinks it needs a web application or not. The first thing you can do to help it is to just leave the servlet API dependencies off the classpath. If you can’t do that (e.g. you are running 2 applications from the same code base) then you can explicitly callsetWebEnvironment(false)
on yourSpringApplication
instance, or set theapplicationContextClass
property (through the Java API or with external properties). Application code that you want to run as your business logic can be implemented as aCommandLineRunner
and dropped into the context as a@Bean
definition.
翻译
71.5 创建非Web应用程序
并不是所有的Spring应用都必须是Web应用(或者 WebService)。如果你想在main方法执行一些代码,但是也需要引导Spring应用设置基础框架。然而使用SpringBoot的
SpringApplication特性就变得容易多了。一个SpringApplication
改变其上下文ApplicationContext
根据他是否是web应用。第一件事情你可以做的就是把servlet API的依赖从根路径移除掉。如果不能这么做(比如两个应用共用一段基础代码)那么你可以使用SpringApplication实例
设置setWebEnvironment(false)
或者设置applicationContextClass
属性(通过java API或者外部属性文件配置)。希望运行自己业务逻辑的应用程序代码可以实现CommandLineRunner然后通过@Bean放入Context(上下文)中。