XML Application Context - bhudevi0924/Spring-boot GitHub Wiki

  1. ClassPathXmlApplicationContext: Loads xml configuration files from the classpath.

        import org.springframework.context.support.ClassPathXmlApplicationContext;
    
        public class Main {
            public static void main(String[] args) {
                // Load the Spring configuration file(s) from the classpath
                ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
                // Retrieve beans from the Spring container
                Bean_name bean = context.getBean("bean_Id", Bean_name.class);
    
                // Use the beans
                bean.method_name();
    
                // Close the context when no longer needed
                context.close();
            }
        }
    
  2. FileSystemXmlApplicationContext: Loads configuration files from the file system (full path / location of the file).

    • Allows configuration files to be loaded from any location in the file system.

    • It lacks web specific features of WebXmlApplicationContext.

      import org.springframework.context.support.FileSystemXmlApplicationContext;

      public class Main { public static void main(String[] args) { // Load the Spring configuration file(s) from the file system FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("path/to/applicationContext.xml");

            // Retrieve beans from the Spring container
            Bean_name bean = context.getBean("Bean_Id", Bean_name.class);
      
           // Use the beans
           bean.method_name();
      
           // Close the context when no longer needed
           context.close();
       }
      

      }

  3. WebXmlApplicationContext: Used within a web application context, loaded by any web server(Tomcat, Jetty etc...) that supports Java server.

    • Loads XML configuration files from the WEB-INF directory in the application.

      import org.springframework.web.context.support.WebXmlApplicationContext;

      public class Main { public static void main(String[] args) { // Load the Spring configuration file(s) from the WEB-INF directory WebXmlApplicationContext context = new WebXmlApplicationContext("path/to/applicationContext.xml");

            // Retrieve beans from the Spring container
            bean_name bean = context.getBean("bean_Id", bean_name.class);
      
            // Use the beans
            bean.someMethod();
      
            // Close the context when no longer needed
            context.close();
        }
      

      }