Spring 零碎整理 以后自己用的到

来源:互联网 发布:微商和淘宝哪个东西贵 编辑:程序博客网 时间:2024/06/01 09:02

明确注册一个BeanFactoryPostProcessor使用BeanFactory实现时,您必须编写代码如下:

XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));// bring in some property values from a Properties filePropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();cfg.setLocation(new FileSystemResource("jdbc.properties"));// now actually do the replacementcfg.postProcessBeanFactory(factory);

The ResourceLoader

The ResourceLoader interface is meant to be implemented by objects that can return (i.e. load) Resource instances.

public interface ResourceLoader {    Resource getResource(String location);}

All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances.

When you call getResource() on a specific application context, and the location path specified doesn’t have a specific prefix, you will get back a Resource type that is appropriate to that particular application context. For example, assume the following snippet of code was executed against a ClassPathXmlApplicationContext instance:

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

What would be returned would be a ClassPathResource; if the same method was executed against a FileSystemXmlApplicationContext instance, you’d get back aFileSystemResource. For a WebApplicationContext, you’d get back a ServletContextResource, and so on.

As such, you can load resources in a fashion appropriate to the particular application context.

On the other hand, you may also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix:

Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");

Similarly, one can force a UrlResource to be used by specifying any of the standard java.net.URL prefixes:

Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");

The following table summarizes the strategy for converting Strings to Resources:

Table 5.1. Resource strings

PrefixExampleExplanation

classpath:

classpath:com/myapp/config.xml

Loaded from the classpath.

file:

file:/data/config.xml

Loaded as a URL, from the filesystem. [1]

http:

http://myserver/logo.png

Loaded as a URL.

(none)

/data/config.xml

Depends on the underlying ApplicationContext.

[1] But see also Section 5.7.3, “FileSystemResource caveats”.


0 0