Using Spring in a standalone application

Solution 1:

  1. Create the standalone application with maven, as pointed here:

    Create a standalone application with Maven

  2. Put the applicationContext in classpath, and load it in the main class as follows:

    ClassPathXmlApplicationContext ctx = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
    

    See full article here:

    http://www.devdaily.com/blog/post/java/load-spring-application-context-file-java-swing-application

Solution 2:

Here's a simple example with 2 classes. Wrote in groovy for ease of reading, but will run for you in java too with proper syntax tweaks

Here's your main:

class Main {

    static void main(String[] args) {
        def ctx = new AnnotationConfigApplicationContext()
        ctx.register(AppConfig.class)
        ctx.refresh()

        def runner = ctx.getBean("mainRunner")
        runner.run()
    }

    void run() {
        println "running from bean"
    }
}

Here's your config bean:

@Configuration
class AppConfig {

    @Bean
    Main mainRunner() {
        new Main()
    }
}

Solution 3:

AppFuse provides different demo applications, all the source code can be downloaded using maven. You can get the complete code of this demo application which is build using Spring MVC,Spring, Hibernate.

Yes this is a web application, you can dig into it and convert it to a stand alone one.