I. Overview
When you encounter a spring configuration file that is not loaded in the project, simply analyze it and write this article memo!
II. Resource requirements for testing
Testbean.java
public class TestBean { public TestBean(){ System.out.println(this.getClass().getName().concat(" init !")); } public String getTestStr() { return "testStr"; }}
Applicationcontext.xml
<bean id="testBean" class="com.bean.TestBean" />
Second, the difference 2.1 Classpathxmlapplicationcontext use method
Classpathxmlapplicationcontext will go to the ClassPath path by default. The ClassPath path refers to the compiled classes directory.
Example:
@TestPublicvoidTestbean(){Single configuration file mode one beanfactory beanfactory=New Classpathxmlapplicationcontext ( "Applicationcontext.xml"); //single profile mode two beanfactory beanfactory=new Classpathxmlapplicationcontext ( "Classpath:applicationContext.xml"); //multiple configuration Files beanfactory beanfactory=new Classpathxmlapplicationcontext (new string[]{ " Applicationcontext.xml "}); //absolute path must be added "file:" prefix beanfactory beanfactory = new Classpathxmlapplicationcontext ( "file:e:\workspace\idea_workspace\spring\springtest\ Src\main\resources\applicationcontext.xml "); Testbean bean= (Testbean) Beanfactory.getbean ( "Testbean"); Assertequals (" Teststr ", Bean.getteststr ());}
To run the sample you will find that "classpath:" is the default.
If it is an absolute path, you need to add a "file:" prefix, not the default.
2.2 Filesystemxmlapplicationcontext How to use
Filesystemxmlapplicationcontext default is to go to the project under the path of loading, can be a relative path, can also be an absolute path, if the absolute path, "file:" prefix can default.
Example:
@TestPublicvoid Testbean () {Classes Directory Beanfactory beanfactory=New Filesystemxmlapplicationcontext ("Classpath:applicationContext.xml");Project path relative path Beanfactory beanfactory=new filesystemxmlapplicationcontext ( "src\\main\\resources\ \applicationcontext.xml "); //multi-profile beanfactory beanfactory=new Filesystemxmlapplicationcontext (new String[]{ "Src\\main\\resources\\applicationcontext.xml"}); //absolute directory beanfactory beanfactory=new Filesystemxmlapplicationcontext (new String[]{ "E:\\workspace\\idea_workspace\\spring\\springtest\\src\\main\\resources\\applicationcontext.xml "}); Testbean bean= (Testbean) Beanfactory.getbean ( "Testbean"); Assertequals (" Teststr ", Bean.getteststr ());}
The difference between classpathxmlapplication and Filesystemxmlapplicationcontext in spring