Several ways to read XML configuration files and get beans in spring

Source: Internet
Author: User
Tags abstract relative

There are several ways to get the class instances managed by the spring framework, as follows:

Method One: Save the ApplicationContext object at initialization time
Code:
ApplicationContext ac = new Filesystemxmlapplicationcontext ("Applicationcontext.xml");
Ac.getbean ("Beanid");
Description
This approach applies to standalone applications that use the spring framework, requiring the program to manually initialize the spring with a configuration file.


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

Import Org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext AC1 = webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC)
ApplicationContext AC2 = webapplicationcontextutils.getwebapplicationcontext (ServletContext SC)
Ac1.getbean ("Beanid");
Ac2.getbean ("Beanid");
Description
This method is suitable for the B/s system with spring Framework, obtains the ApplicationContext object through the ServletContext object, and obtains the required class instance through it.
The difference between the above two tool methods is that the former throws an exception when it gets failed, and the latter returns null.


Method Three: Inherit from abstract class Applicationobjectsupport
Description
Abstract class Applicationobjectsupport provides the Getapplicationcontext () method, which can be easily obtained to 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
Description
Similar to the above method, call Getwebapplicationcontext () to get Webapplicationcontext

Method Five: Implement Interface Applicationcontextaware
Description
Implement the interface's Setapplicationcontext (ApplicationContext context) method and save the ApplicationContext object. When spring initializes, the ApplicationContext object is injected through this method.

The above method is suitable for different situations, please choose the appropriate method according to the specific situation.

It is worth mentioning that the classes used in the system above are actually tightly coupled to the spring framework, because these classes know that they are running on the spring framework, so the system should minimize such applications and make the system as independent of the current operating environment as possible. Try to obtain the required service provider by means of Di.

I think that the method of five more feasible, you can design a tool class, specifically to get the class in spring. Reduce the intrusion of business code.

Reading an XML file

/**
* 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");

/*
* Use Properties
* To place Bean.properties in the Classpath-source folder (SRC) directory
*/

Here are two techniques: using spring to read the properties file and to read with Java.util.Properties
(i) using spring to read the properties file
Using Org.springframework.beans.factory.support.PropertiesBeanDefinitionReader to read property files

Construct the following Config.properties file properties code

Userdao.class=com.spring.dao.userdao

The "Userdao" name in the

Property file is the Bean's alias setting, and the. Class is used to specify the source of the class.
then use Org.springframework.beans.factory.support.PropertiesBeanDefinitionReader to read the properties file
   Beandefinitionregistry reg = new Defaultlistablebeanfactory ();
   Propertiesbeandefinitionreader reader = new Propertiesbeandefinitionreader (reg);
   reader.loadbeandefinitions (New Classpathresource ("Config.properties"));
   Beanfactory factory = (beanfactory) reg;
   Userdao Userdao = (Userdao) factory.getbean ("Userdao");
(ii) Use Java.util.Properties to read the property file
1.    String str=file.separator;
        InputStream Path=this.getservletcontext (). getResourceAsStream (str+ " Web-inf "+str+" Classes "+str+" password.properties ");
       //inputstream InputStream = This.getclass (). getClassLoader (). getResourceAsStream ("Password.properties");

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

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 Org.springframework.core.io.ClassPathResource;

Classpathresource cr = new Classpathresource ("password.properties");//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 not working

3. Read with Xmlwebapplicationcontext

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


Xmlwebapplicationcontext's construction does not have the parameters, the API file will be discovered, the location of the preset will point to the/web-inf/applicationcontext.xml files. Use its public static default_config_location to obtain this file name. Since I'm using MyEclipse, the Presets will have a "/webroot" in front of Web-inf, so if there are some web-related programs in Web project that want to use the context (for example, some of the "M" parts of the MVC structure), you can't use Xmlwebapplicationcontext to read bean definitions because the default location would be a "WebRoot".
Even in Web. XML, redefine contextconfiglocation in Dispatcherservlet definition (this definition can override the default in Xmlwebapplicationcontext _config_location value), because a web-related program does not pass the definition of XML. I haven't tried it yet. Xmlwebapplicationcontext get bean definitions, using classpathxmlapplicationcontext will be faster.


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. Read with Filesystemresource

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 important to note that, with Filesystemresource, the configuration file must be placed in the project direct directory, or an absolute path, or an exception will be thrown that cannot find the file.



5. Read with Filesystemxmlapplicationcontext

You can specify a relative path to the XML definition file or an absolute path 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");
Without Classpath, it's from the current working directory.

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: info-contact@alibabacloud.com 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.