单个xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.fxyh.ioc.User"> <property name="name" value="zhangsan"/> <property name="password" value="123456"/> </bean> </beans>多个xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-user.xml", "classpath:applicationContext-department.xml"); applicationContext-department.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="department" class="com.fxyh.ioc.Department"> <property name="id" value="1"/> <property name="name" value="lisi"/> <property name="location" value="123"/> </bean> </beans> applicationContext-user.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.fxyh.ioc.User"> <property name="name" value="zhangsan"/> <property name="password" value="123456"/> </bean> </beans>如果xml文件很多怎么办,不可能所有都写出来吧那么如下解决办法
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext-*.xml");注意:这里一定不能省略classpath:*
否则容器不会加载模糊匹配的配置文件
使用import的方法集中到单一xml中
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContextImport.xml"); applicationContextImport.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <import resource="applicationContext-user.xml"/>--> <!-- <import resource="applicationContext-department.xml"/>--> <import resource="classpath*:applicationContext-*.xml"/> </beans>这里import也可以使用模糊匹配,也可以引入单个xml。
使用FileSystemXmlApplicationContext
String path = url.getPath(); path = URLDecoder.decode(path, "UTF-8"); ApplicationContext context = new FileSystemXmlApplicationContext(path);这里的文件名必须为单个文件。
使用XmlBeanFactory(已过时,不建议使用)
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContextImport.xml"));