spring中加载Bean配置文件的常用方式
Spring中加载Bean配置文件的常用方式有两种,一种是通过实例化FileSystemXmlApplicationContext类的方式加载Bean,
另一种是通过实例化ClassPathXmlApplicationContext类的方式加载Bean.现举例如下,已做记录.
1.FileSystemXmlApplicationContext
(1)默认从项目工作路径开始查找,是相对路径
ApplicationContext applicationContext1 = new FileSystemXmlApplicationContext( "src/main/java/org/springframework/abc/demo/beans.xml");
(2)如果加上file前缀,则表示绝对路径
ApplicationContext applicationContext2 = new FileSystemXmlApplicationContext( "file:E:/SpringSources/src/main/java/org/springframework/abc/demo/beans.xml");
2.ClassPathXmlApplicationContext
(1)没有前缀,默认为项目的classpath下相对路径
ApplicationContext applicationContext3 = new ClassPathXmlApplicationContext("beans.xml");
(2)加上classpath前缀,表示项目的classpath下相对路径
ApplicationContext applicationContext4 = new ClassPathXmlApplicationContext( "classpath:beans.xml");
3.DEMO代码如下
public class Test { public static void main(String[] args) { ApplicationContext applicationContext1 = new FileSystemXmlApplicationContext( "file:E:/SpringSources/src/main/java/org/springframework/abc/demo/beans.xml"); System.out.println(applicationContext1.getBean("person")); ApplicationContext applicationContext2 = new FileSystemXmlApplicationContext( "src/main/java/org/springframework/abc/demo/beans.xml"); System.out.println(applicationContext2.getBean("person")); ApplicationContext applicationContext3 = new FileSystemXmlApplicationContext( "classpath:beans.xml"); System.out.println(applicationContext3.getBean("person")); ApplicationContext applicationContext4 = new ClassPathXmlApplicationContext( "beans.xml"); System.out.println(applicationContext4.getBean("person")); ApplicationContext applicationContext5 = new ClassPathXmlApplicationContext( "classpath:beans.xml"); System.out.println(applicationContext5.getBean("person")); } }
相关推荐
lukezhong 2020-10-14
tangxiong0 2020-09-03
编程点滴 2020-07-29
itjavashuai 2020-07-04
凯哥Java 2020-04-25
杜鲁门 2020-11-05
与卿画眉共浮生 2020-10-14
YangHuiLiang 2020-08-06
Sweetdream 2020-08-03
smalllove 2020-07-27
iconhot 2020-07-05
XGQ 2020-07-04
MicroBoy 2020-07-04
zmysna 2020-07-04
willluckysmile 2020-06-29
CoderBoy 2020-06-28
爱莲说 2020-06-26
itjavashuai 2020-06-25