Application context and resource path

Source: Internet
Author: User
Tags file url
4.7. application context andResourcePath
Spring provides generic access to resource files. applicationcontext inherits Org. springframework. core. io. resource interface, org. springframework. core. io. the resource interface represents any physical resource, which inherits from Org. springframework. core. io. inputstreamsource; its sub-classes include bytearrayresource, classpathresource, descriptiveresource, filesystemresource, inputstreamresource, portletcontextresource, servletcontextresource, and urlresource. The following are commonly used:
  1. Classpathresource: The classpathresource is accessed in a class path. classpath: as the name suggests, it is the output path of the class file. You can use Java build path-> source-> Output Folder/default Output Folder to check whether the Java project is bin by default or the web project is classes by default.
  2. Filesystemresource: access through filesystemresource in the relative path of the absolute path of the file system; for example: (1) absolute path: Resource resource = context. getresource ("file: C:/workspace/OMS/config/applicationContext-ibatis.xml "). (2) Relative Path: If you use relative paths, pay attention to the root directory. For example, in eclipse, its root directory is your project directory as your root directory. Resource resource = context. getresource ("config/applicationContext-ibatis.xml ").... Then, because XML files are used, org. springframework. beans. factory. XML. xmlbeanfactory class, xmlbeanfactory implements Org. springframework. beans. factory. beanfactory interface, used to read definitions and create beanfactory instances. Beanfactory factory = new xmlbeanfactory (Resource); test AA = (TEST) factory. getbean ("applicationlistdao1 ");
  3. Servletcontextresource: access through servletcontextresource relative to the Web application root directory. For example, resource = context. getresource ("WEB-INF/CONF/applicationContext-ibatis.xml ").
  4. Urlresource: access resources through java.net. url. Of course, it also supports file format, such as "file :"

After obtaining the resource interface instance, you can use GetFile (), getinputstream (), and other methods to operate the resource file.

The example of the resource interface is only an abstract representation of the resource file. The specified resource may not exist. You can use exists () for testing.

 

Let's take a look at the definition of the resource interface: see this connection: Resource interface in spring Http://blog.csdn.net/myyate/archive/2007/10/10/1818714.aspx

Define file access:

Resource resource = new classpathresource ("bean. xml ");

Beanfactory factory = new xmlbeanfactory (Resource );

Hellobean Hello = (hellobean) Factory. getbean ("hellobean ");

The classpathresource above can be filesystemresource, inputstreamresource, servletcontextresource, or urlresource;

  • Loading a definition file, As follows:

// Bean. xml

<? XML version = "1.0" encoding = "UTF-8"?>

<! Doctype beans public "-// spring/DTD bean/EN"

Http://www.springframework.org/dtd/spring-beans.dtd>

<Beans>

<Bean id = "hellobeanofjustin" class = "onlyfun. Caterpillar. hellobean">

<Property name = "helloword"> <value> hello! Justin! </Value> </property>

</Bean>

<Bean id = "hellobeanofcaterpillar" class = "onlyfun. Caterpillar. hellobean">

<Property name = "helloword"> <value> hello! Caterpillar! </Value> </property>

</Bean>

</Beans>

Operation:

Resource resource = new classpathresource ("bean. xml ");

Listablebeanfactory factory = new xmlbeanfactory (Resource );

Map hellobeans = factory. getbeansoftype (hellobean. Class, false, false );

  • Loading of multiple definition files:

Beandefinitionregistry Reg = new defaultlistablebeanfactory ();

Xmlbeandefinitionreader = new xmlbeandefinitionreader (REG );

// Load Bean

Reader. loadbeandefinitions (New classpathresource ("bean1.xml "));

Reader. loadbeandefinitions (New classpathresource ("bean2.xml "));

....

// Obtain Bean

Beanfactory BF = (beanfactory) reg;

Object o = BF. getbean ("hellobean ");

Org. springframework... beans. Factory. Support. beandefinitionregistry is required.

And org. springframework... beans. Factory. Support. defaultlistablebeanfactory. xmlbeandefinitionreader

Rod Johnson, the creator of spring, suggested using applicationcontext to replace beanfactory. in the class that implements applicationcontext, the most commonly used is about three. Org. springframework. Context. Support. filesystemxmlapplicationcontext can specify the relative or absolute path of the XML definition file to read the definition file. Org. springframework. Context. Support. classpathxmlapplicationcontext reads the definition file from the classpath setting path. Org. springframework. Web. Context. Support. xmlwebapplicationcontext in the file architecture of a web application, specify a relative location to read the definition file. 4.7.1. Construct application context

 

 

The application context constructor usually uses a string or string array as the location path for resources (such as the XML file defined by context. When such a path does not have a prefixResourceThe type will be created through this path and used to load bean definitions, depending on the application context you specified. For example, if you use the following code to createClassPathXmlApplicationContext:

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

The bean definitions are loaded and used through classpath.ClassPathResource. And if you createFileSystemXmlApplicationContext:

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

The bean definitions are loaded and used from the current working directory through the file system.FileSystemResource.

Note that if the positioning PATH uses the classpath prefix or the standard URL prefix, it will overwrite the defaultResourceType (FileSystemResource). Therefore, the followingFileSystemXmlApplicationContext...

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");

... It will actually load its bean definition through classpath. However, it is stillFileSystemXmlApplicationContext. If it is treatedResourceLoaderThen, any path without a prefix will still be treated as a file system path.

 

4.7.1.1. Create ClassPathXmlApplicationContextInstance-Overview

     ClassPathXmlApplicationContextMultiple constructor methods are provided to facilitate initialization. But its core is that if we only provide a string array composed of XML file names (without complete path information), andAlsoProvidedClass; ThenClassPathXmlApplicationContextThe path information is extracted from the given class.

I hope to explain this through an example. Assume that the directory structure is as follows:

 com/  foo/        services.xml        daos.xml        MessengerService.class

By'services.xml'And'daos.xml'BeanClassPathXmlApplicationContextThe instance will be instantiated like this...

ApplicationContext ctx = new ClassPathXmlApplicationContext(    new String[] {"services.xml", "daos.xml"}, MessengerService.class);

For more informationClassPathXmlApplicationContextFor details about multiple constructor methods, see its javadocs.

4.7.2. wildcard characters in the resource path in the application context Constructor

The value of the resource path in the application context constructor can be a simple path (as shown above), that is, one-to-one ing to a target resource; or it can contain a special "classpath *: "prefix and ant-style Regular Expression (using springPathMatcherTool ). Wildcard characters can be used for both.

One use of this mechanism is component-type application assembly. All components can be defined using the general positioning path "publish" context, so that when the sameclasspath*:When the prefix is used to create the final application context, all component fragments are automatically loaded.

Note that this wildcard is only used in the resource path of the application context Constructor (or directly in the class hierarchy ).PathMatcherIs valid, it will be parsed during the construction. This correspondsResourceThe type itself is not associated. You cannot useclasspath*:Prefix to construct the actualResource. <That is, it cannot be used in a statement like thisClasspath *: prefix,Resource resource = context. getresource ("WEB-INF/CONF/applicationContext-ibatis.xml "). ?>

4.7.2.1. Ant Pattern

When it contains the ant pattern, for example:

     /WEB-INFapplicationContext.xml     file:C:/some/pathapplicationContext.xml

The parser attempts to parse wildcards in a pre-defined complex process. It generates a resource based on the last non-Wildcard segment in the path and obtains a URL from it. If the URL is not a "jar:" URL or a variable of a specific container (for example"zip:", In WebSphere"wsjar"And so on), you can getjava.io.FileAnd use it to parse wildcards from the file system. If it is a jar URL, the parser can obtainjava.net.JarURLConnectionOr manually parse the jar URL, and then traverse the JAR file to parse the wildcard.

4.7.2.1.1. Potential portability

If the given path is already a File URL (either explicitly or implicitly), the wildcard character can be transplanted because the basic resourceloader is for the file system.

If the given path is a classpath location, the parser must pass throughClassloader.getResource()Call the URL to obtain the last non-Wildcard path segment. Because it is only a path node (not a final file), it is not exactly defined (inClassLoaderIn javadocs) What type of URL will be returned here. Generally, when the classpath resource is resolved to a file system location,java.io.FileWhen it is resolved to the jar location, a jar URL is returned. Of course, this operation involves portability.

If you get a jar URL from the last non-Wildcard segment, the parser will be able to getjava.net.JarURLConnectionOr manually parse the jar URL to traverse the JAR file and parse the wildcard. This operation works normally in most environments, but there are exceptions. Therefore, we strongly recommend that you thoroughly test the parsing of the jar resource wildcard in a specific environment before official use.

Continued

4.7.2.2. classpath*:Prefix

When constructing an XML-based application context, the path string may use a specialclasspath*:Prefix:

ApplicationContext ctx =    new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");

This prefix indicates that all classpath resources that match the given name should be obtained (where, this is often calledClassLoader.getResources(...)), And then combine all the resources into the final application context definition.

Classpath *: portability

Classpath with wildcards depends on the underlying classloader'sgetResources()Method. Currently, most application servers provide their own classloader implementations, which may behave differently when processing jar files. To testclasspath*:Effective or not, you can simply use classloader to load a file from the jar file in classpath:getClass().getClassLoader().getResources("<someFileInsideTheJar>"). Run the test on two files with the same name in different locations. If the result is incorrect, check the document of the application server, especially the settings that may affect the classloader behavior.

"classpath*:"Prefix can also be combined with other parts of the Location PathPathMatcherUse pattern together, for example"classpath*:META-INFservice-context.xml

The parser will excludegetResource("com/mycompany"); The returned (first) URL. If the base package node exists in multiple classloader locations, the final resource to be searched may not be found. Therefore, it is best to use the ant pattern in this case"classpath*:"To search for all class paths including the root package.

4.7.3. FileSystemResourcePrompt

One does not matchFileSystemApplicationContextBoundFileSystemResource(That isFileSystemApplicationContextNot reallyResourceLoader), The absolute and relative paths will be distinguished as you expected. The relative path is relative to the current working directory, and the absolute path is relative to the root directory of the file system.

For forward compatibility purpose, whenFileSystemApplicationContextYesResourceLoaderIt will change.FileSystemApplicationContextWill make all boundFileSystemResourceThe instance regards absolute paths as relative paths, regardless of whether they start with a backslash. That is to say, the following meanings are the same:

ApplicationContext ctx =    new FileSystemClassPathXmlApplicationContext("conf/context.xml");
ApplicationContext ctx =    new FileSystemClassPathXmlApplicationContext("/conf/context.xml");

The following is the same: (although it makes sense to distinguish them, one of them is the relative path, and the other is the absolute path ).

FileSystemXmlApplicationContext ctx = ...;ctx.getResource("some/resource/path/myTemplate.txt");
FileSystemXmlApplicationContext ctx = ...;ctx.getResource("/some/resource/path/myTemplate.txt");

In fact, if you really need to use absolute paths, you 'd better not use them.FileSystemResourceOrFileSystemXmlApplicationContextTo determine the absolute path. We can usefile:Use the URL prefix forciblyUrlResource.

// actual context type doesn't matter, the Resource will always be UrlResourcectx.getResource("file:/some/resource/path/myTemplate.txt");
// force this FileSystemXmlApplicationContext to load it's definition via a UrlResourceApplicationContext ctx =    new FileSystemXmlApplicationContext("file:/conf/context.xml");
 

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.