68.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 the SpringApplication
features of Spring Boot. A SpringApplication
changes its ApplicationContext
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 call setWebEnvironment(false)
on your SpringApplication
instance, or set the applicationContextClass
property (through the Java API or with external properties). Application code that you want to run as your business logic can be implemented as a CommandLineRunner
and dropped into the context as a @Bean
definition.