Classpathresource, Classpathxmlresource, Classpathxmlapplicationcontext

Source: Internet
Author: User

Spring Read configuration file method

Method One: Save the ApplicationContext object when initializing
ApplicationContext ac = new Filesystemxmlapplicationcontext ("Applicationcontext.xml");
Ac.getbean ("Beanid");
This approach applies to stand-alone applications that use the spring framework, and requires programs to manually initialize spring with a configuration file.

Method Two: Get the ApplicationContext object from the tool class provided by spring


ApplicationContext AC1 = webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC)
ApplicationContext AC2 = webapplicationcontextutils.getwebapplicationcontext (ServletContext SC)
Ac1.getbean ("Beanid");
Ac2.getbean ("Beanid");
This approach is suitable for the B/s system using the spring framework, obtaining the ApplicationContext object through the ServletContext object, and then obtaining the required class instances through it.
The difference between the above two tools is that the former throws an exception when a failure is obtained, and the latter returns null.

Method Three: Inherit from abstract class Applicationobjectsupport
Abstract class Applicationobjectsupport provides a Getapplicationcontext () method that can be easily obtained from ApplicationContext. When spring initializes, the ApplicationContext object is injected through the Setapplicationcontext (ApplicationContext context) method of the abstract class.

Method Four: Inherit from abstract class Webapplicationobjectsupport
Similar to the above method, call Getwebapplicationcontext () to get Webapplicationcontext

Method Five: Implement Interface Applicationcontextaware
Implements the Setapplicationcontext (ApplicationContext context) method of the interface and saves the ApplicationContext object. When spring initializes, the ApplicationContext object is injected by this method.

The above methods are suitable for different situations, please choose the appropriate method according to the specific circumstances.

Special statement:

When you import another file in spring, use the Classpathxmlresource

When using dynamic loading, use the Classpathxmlapplicationcontext

I don't know why.

What is worth mentioning here is that the classes used in these methods in the system are actually tightly coupled to the spring framework, because these classes are known to run on the spring framework, so in the system, you should minimize such applications so that the system is as independent as possible from the current running environment. Try to get the service providers you need through DI.

Two. Reading XML files

* Using Xmlbeanfactory (Resource Resource)
* Here resource must be in XML format
* Resource includes: Abstractresource, Classpathresource, Filesystemresource,
* Inputstreamresource, Servletcontextresource, Urlresource

* Using Inputstreamresource (InputStream inputstream)
* To place the applicationcontext.xml in the project root directory
InputStream is = null;
try {
is = new FileInputStream ("Applicationcontext.xml");
catch (FileNotFoundException e) {
E.printstacktrace ();
Resource Resource = new Inputstreamresource (IS);
Beanfactory factory = new Xmlbeanfactory (Resource);
Userdao Userdao = (Userdao) factory.getbean ("Userdao");

* Using Properties
* To place the in the Classpath-source folder (SRC) directory

Here are two techniques: using spring to read properties files and using Java.util.Properties to read
(i) using spring to read properties files
Using to read property files

Constructs the following file properties code


The "Userdao" name in the

property file is the alias setting for the Bean. Class is used to specify the source of the class.
then use to read the property file
   Beandefinitionregistry reg = new Defaultlistablebeanfactory ();
   Propertiesbeandefinitionreader reader = new Propertiesbeandefinitionreader (reg);
   reader.loadbeandefinitions (New Classpathresource (""));
   Beanfactory factory = (beanfactory) reg;
   Userdao Userdao = (Userdao) factory.getbean ("Userdao");
(ii) Read the property file using Java.util.Properties
1.    String str=file.separator;
         InputStream Path=this.getservletcontext (). getResourceAsStream (str+ "Web-inf" +str+ " Classes "+str+" ");
       //inputstream InputStream = This.getclass (). getClassLoader (). getResourceAsStream ("");

/*file filepath=new File (This.getservletcontext (). Getrealpath (str+ "Web-inf" +str+ "classes") +str+ " ");

InputStream path=new FileInputStream (filepath);
Properties Pros = new properties ();
try {
Pros.load (path);
catch (IOException ex) {
System.out.println ("File is not exist");
Errormessage= "Resource file does not exist";
System.out.println ("Username:" +p.getproperty ("username") + ", Password:" +p.getproperty ("password"));

2. Import;

Classpathresource cr = new Classpathresource ("")//Reload Spring frame
Properties Pros = new properties ();
try {
Pros.load (Cr.getinputstream ());
catch (IOException ex) {
System.out.println ("File is not exist");
Errormessage= "Resource file does not exist";

1. Using Classpathxmlapplicationcontext

XML files can be read from Classpath

(1) ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Userdao Userdao = (Userdao) context.getbean ("Userdao");

(2) classpathxmlapplicationcontext resource = new Classpathxmlapplicationcontext (New string[]{" Applicationcontext-ibatis-oracle.xml "," Applicationcontext.xml "," Applicationcontext-data-oracle.xml "});

Beanfactory factory = resource;

Userdao Userdao = (Userdao) factory.getbean ("Userdao");

2. Using Classpathresource

XML files can be read from Classpath

Resource cr = new Classpathresource ("Applicationcontext.xml");

Beanfactory bf=new Xmlbeanfactory (CR);

Userdao Userdao = (Userdao) bf.getbean ("Userdao");

Loading an XML file Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer does not work

3. Using Xmlwebapplicationcontext to read

From the file schema of the Web application, specify a relative position to read the definition file.

Xmlwebapplicationcontext CTX = new Xmlwebapplicationcontext ();
Ctx.setconfiglocations (new string[] {"/web-inf/applicationcontext.xml");
Ctx.setservletcontext (Pagecontext.getservletcontext ());
Ctx.refresh ();
Userdao Userdao = (Userdao) ctx.getbean ("Userdao");

4. Using Filesystemresource to read

Resource rs = new Filesystemresource ("D:/tomcat/webapps/test/web-inf/classes/applicationcontext.xml");
Beanfactory factory = new Xmlbeanfactory (RS);
Userdao Userdao = (Userdao) factory.getbean ("Userdao");

It is worth noting that, with Filesystemresource, the configuration file must be placed in the project direct directory, or the absolute path should be specified, or it will throw an exception that cannot find the file

5. Using Filesystemxmlapplicationcontext to read

You can specify the relative path or absolute path of the XML definition file to read the definition file.

Method One:

String[] path={"Webroot/web-inf/applicationcontext.xml", "Webroot/web-inf/applicationcontext_task.xml"};
ApplicationContext context = new Filesystemxmlapplicationcontext (path);

Method Two:

String path= "Webroot/web-inf/applicationcontext*.xml";
ApplicationContext context = new Filesystemxmlapplicationcontext (path);

Method Three:
ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Classpath: Address");
No classpath words are from the current working directory

Start the Spring framework


ApplicationContext context = new Classpathxmlapplicationcontext (
"Beans.xml", This.getclass ());


. Resource res = new Classpathresource ("1.xml");
Beanfactory factory = new Xmlbeanfactory (res);
SayHello bean1 = (SayHello) factory.getbean ("Hello");

1. For simple testing with applicationcontext, get the Bean instance (object) defined in spring. You can use:

ApplicationContext ac = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Registerdao Registerdao = (Registerdao) ac.getbean ("Registerdao");

If it is more than two:
ApplicationContext ac = new Classpathxmlapplicationcontext (new string[]{"Applicationcontext.xml", "Dao.xml"});

Or use wildcard characters:
ApplicationContext ac = new Classpathxmlapplicationcontext ("Classpath:/*.xml");

Second, the classpathxmlapplicationcontext[can only read in the web-info/classes directory of the configuration file] and Filesystemxmlapplicationcontext difference

Classpath: prefix is not required, the default is to refer to the project under the Classpath path;
If you want to use an absolute path, you need to add the file: prefix to indicate that this is an absolute path;

For Filesystemxmlapplicationcontext:
Two types are represented by default:

1. Without the letter is the project work path, namely the project root directory;
2. The disk character represents the absolute path of the file.

If you want to use the classpath path, you need to prefix classpath:

public class Helloclient {

Protected static Final log = Logfactory.getlog (Helloclient.class);

public static void Main (string[] args) {
Resource Resource = new Classpathresource ("Appcontext.xml");
Beanfactory factory = new Xmlbeanfactory (Resource);

Using the Classpath path
ApplicationContext factory = new Classpathxmlapplicationcontext ("Classpath:appcontext.xml");
ApplicationContext factory = new Classpathxmlapplicationcontext ("Appcontext.xml");

Classpathxmlapplicationcontext uses the file prefix to use an absolute path.
ApplicationContext factory = new Classpathxmlapplicationcontext ("File:f:/workspace/example/src/appcontext.xml");

The path to the file system, which defaults to the root path of the project
ApplicationContext factory = new Filesystemxmlapplicationcontext ("Src/appcontext.xml");
ApplicationContext factory = new Filesystemxmlapplicationcontext ("Webroot/web-inf/appcontext.xml");

The classpath: prefix is used so that filesystemxmlapplicationcontext can also read the relative path under Classpath
ApplicationContext factory = new Filesystemxmlapplicationcontext ("Classpath:appcontext.xml");
ApplicationContext factory = new Filesystemxmlapplicationcontext ("File:f:/workspace/example/src/appcontext.xml") ;

No file prefix
ApplicationContext factory = new Filesystemxmlapplicationcontext ("F:/workspace/example/src/appcontext.xml");
Ihelloworld HW = (ihelloworld) factory.getbean ("Helloworldbean"); (Hw.getcontent ("Luoshifei"));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.