2011年9月5日 星期一

[Java] Example on Spring's ApplicationContext

My example is based on Simple Spring Example Project.

Step by step:
  1. Create a new Java project in Eclipse. Use 'nothing' package to organize my project.
  2. Add all Spring framework and Apache Commons Logging JAR files into libraries.
  3. Add 'ApplicationContextExample.java', 'IApplicationContextService.java', 'ApplicationContextService.java' and 'applicationContextExample.xml' of 'Simple Spring Example Project' into the project.
    • In ApplicationContextExample.java:
      package nothing;
      ...
      
      public class ApplicationContextExample {
          public static void run() {
              ApplicationContext applicationContextExample 
                  = new ClassPathXmlApplicationContext
                      ("nothing/applicationContextExample.xml");
              ApplicationContextService applicationContextService 
                  = (ApplicationContextService) 
                      applicationContextExample.getBean
                          ("applicationContextService");
              applicationContextService.
                  printExampleClassProperty();
          }
      }
    • In applicationContextExample.xml:
      <bean id="applicationContextService" 
            class="nothing.ApplicationContextService">
          <property name="exampleClassProperty" 
                    value="Spring is running!!!" />
      </bean>
      
  4. Add new Main.Java. It's a delegate class to call ApplicationContextExample.java:
    package nothing;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            ApplicationContextExample.run();
        }
    }
  5. Run!
Enjoy!

沒有留言:

張貼留言