Spring encapsulates various types of resources into a unified Resource interface. Through this Resource interface, you can obtain URL, InputStream, and File objects. Of course, the Resource object may not exist, and InputStream will not be available. If Resource is not a File in the File system, the File object cannot be obtained.
Authorization + PHA + PC9wPjxwcmUgY2xhc3M9 "brush: java;"> public class MyBean {private Resource config; public void setConfig (Resource config) {this. config = config ;}......}
Spring configuration file beans. xml
myConfig.xml
In this way, Spring will inject the resources corresponding to the appropriate myConfig. xml into the myBean object. So how does Spring find the "myConfig. xml" file in the configuration file? There are different results in different environments.
1) if I start the Spring container in the following ways:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Then the system will find the myConfig. xml file in classpath and inject it into the myBean object. Equivalent:
MyBean. setConfig (getClassLoader (). getResource ("myConfig. xml ").
2) if I start Spring in the following ways:
ApplicationContext context = new FileSystemXmlApplicationContext("C:/path/to/beans.xml");
The system will find the myConfig. xml file in the file system. Equivalent:MyBean. setConfig (new File ("myConfig. xml ")).
3) if I use ContextLoader in a Web application to start Spring (/WEB-INF/web. xml snippets are as follows ):
contextConfigLocation
/WEB-INF/beans.xml
org.springframework.web.context.ContextLoaderListener
ContextLoaderListener creates an XmlWebApplicationContext as the Spring container. Therefore, the system will search for myConfig. xml in the root directory of the Web application. Equivalent:
MyBean. setConfig (servletContext. getResource ("myConfig. xml ")).
How does Spring achieve this? In Spring, the ApplicationContext object not only inherits the BeanFactory interface (representing the bean container), but more importantly, it builds a bridge between beans and the runtime environment-All ApplicationContext implements the ResourceLoader interface. Therefore, they can load resources in appropriate ways according to different environments.
In addition, Spring has a special resource representation:
classpath:myConfig.xml
In this way, no matter what the implementation of ApplicationContext is, it will always go to classpath to find the myConfig. xml Resource