第一种:
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) ctx.getBean("user");
第二种:
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
User user1 = (User) bf.getBean("user");
前两种都是按照classpath来解析配置文件
第三种:
FileSystemXmlApplicationContext fct =
new FileSystemXmlApplicationContext("/src/main/resources/applicationContext.xml");
User user2 = (User) fct.getBean("user");
以项目为根路径,配置文件放在class路径下需要补全项目根路径。
第四种:
String rootPath = System.getProperty("user.dir");
BeanFactory bf1 = new XmlBeanFactory(
new FileSystemResource(rootPath+"/src/main/resources/applicationContext.xml"));
User user3 = (User) bf1.getBean("user");
以系统为根路径。
第五种:
注册一个监听,当启动服务时加载配置文件
<!-- web启动读取applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>