ClassPathXmlApplicationContext

The subclass of AbstractXmlApplicationContext is used for standalone applications. It uses the bean-configured XML file from the class path. Sometimes, the application may have more than one configuration file in the classpath, and, accidentally, they may write the definition for the same bean. In such conditions where the application has more than one XML configuration file, the later bean definition from the XML file will override the earlier bean definition. It provides the advantage of writing a new bean definition to replace the previous one.

Let's find out, practically, how the ClassPathXmlApplicationContext container gets initialized. We will use the same Ch01_Container_Initialization project by following these steps:

  1. Create a TestClasspathApplicationContext class under the com.ch01.test package.
  2. Create a new XML file, beans_classpath.xml, in the classpath, just like we created in the previous application.
  3. In the main function, let's write down the following code to initialize the bean factory:
try { 
ApplicationContext context=new
ClassPathXmlApplicationContext
("beans_classpath.xml");
System.out.println("container created successfully");
}
catch (BeansException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

No need to create an XML file as we already created it for the previous example. ClassPathXmlApplicationContext loads beans_classpath.xml from the classpath that contains the beans definitions. (For simplicity, we haven't added any bean definition; we will see it in detail in the next chapter.)

  1. Run the application, which will give the following output, suggesting that the container was created successfully:
Console output
  1. In the Java enterprise application, the project can have multiple configuration files as it's easy to maintain, and it supports modularity as well. To load the multiple bean configuration files, we can use the following code:
try { 
ApplicationContext context1 = new
ClassPathXmlApplicationContext
(new String[] {
"beans_classpath.xml","beans_classpath1.xml" });
}
catch (BeansException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

To use the preceding lines of code, we will need to create beans_classpath1.xml in the classpath.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.20