I want to create spring console application (running from command line with maven for example: mvn exec:java -Dexec.mainClass=\"package.MainClass\").
Is this application
The Spring Reference suggests using ClassPathXmlApplicationContext in the main
method to create the application context, then calling the getBean
method to get an initial reference to a bean from the application context. After writing this same code a few times, you wind up refactoring the boilerplate into this utility class:
/**
* Bootstraps Spring-managed beans into an application. How to use:
*
* - Create application context XML configuration files and put them where
* they can be loaded as class path resources. The configuration must include
* the {@code
} element to enable annotation-based
* configuration, or the {@code }
* element to also detect bean definitions from annotated classes.
* - Create a "main" class that will receive references to Spring-managed
* beans. Add the {@code @Autowired} annotation to any properties you want to be
* injected with beans from the application context.
*
- In your application {@code main} method, create an
* {@link ApplicationContextLoader} instance, and call the {@link #load} method
* with the "main" object and the configuration file locations as parameters.
*
*/
public class ApplicationContextLoader {
protected ConfigurableApplicationContext applicationContext;
public ConfigurableApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Loads application context. Override this method to change how the
* application context is loaded.
*
* @param configLocations
* configuration file locations
*/
protected void loadApplicationContext(String... configLocations) {
applicationContext = new ClassPathXmlApplicationContext(
configLocations);
applicationContext.registerShutdownHook();
}
/**
* Injects dependencies into the object. Override this method if you need
* full control over how dependencies are injected.
*
* @param main
* object to inject dependencies into
*/
protected void injectDependencies(Object main) {
getApplicationContext().getBeanFactory().autowireBeanProperties(
main, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
}
/**
* Loads application context, then injects dependencies into the object.
*
* @param main
* object to inject dependencies into
* @param configLocations
* configuration file locations
*/
public void load(Object main, String... configLocations) {
loadApplicationContext(configLocations);
injectDependencies(main);
}
}
Call the load
method in your application main method. Notice that the Main
class is not a Spring-created bean, and yet you can inject one of its properties with a bean from the application context.
public class Main {
@Autowired
private SampleService sampleService;
public static void main(String[] args) {
Main main = new Main();
new ApplicationContextLoader().load(main, "applicationContext.xml");
main.sampleService.getHelloWorld();
}
}