I’m working on a simple web application with Java and Spring Boot. It reads data from PostgreSQL using MyBatis and provides a JSON API to clients. My app is deployed to the server as a single jar file.
I want to implement a feature that will import data from a dump. The idea is to parse an XML file with data and insert records into PostgreSQL. I want to reuse beans of my application like MyBatis Mappers, MVC models, PostgreSQL connection configuration and so on.
Is it possible to have one jar, that will run web server when I run it like java -jar my-app.jar
and if I executes it with parameters it performs and import: java -jar my-app.jar import dump.xml
?
I wrote default Spring Boot Application Class:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and wrote a class that implements CommandLineRunner
interface:
@Component
public class DbImporter implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// perform import
}
}
I expect that it will be possible not to start web server somehow in case of import task, but I don’t know how to implement this idea. Also I want to write some sort of integration test for DbImporter class. It should create Spring context with all required beans, initializes test database and check DbImporter class logic. When I write something like
@SpringBootTest
public class DbImporterIT {
@Test
void testDataLoading() {
}
}
It initializes context and automatically executes the code of DbImporter, but I want to do it by hands.