ApplicationContext和BeanFacotry区别:
ApplicationContext和BeanFacotry相比,提供了更多的扩展功能,但其主要区别在于后者是延迟加载,如果Bean的某一个属性 没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常;而ApplicationContext则在初始化自身是 检 验,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用ApplicationContext.
方法1
WebApplicationContext appContext=WebApplicationContextUtils. getWebApplicationContext(this.getServlet().getServletContext());
方法2:是从classpath 路径下加载 spring的配置文件
WebApplicationContext appContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
方法3
Resource resource = new FileSystemResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(resource);
方法4
ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
方法5
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"}); // of course, an ApplicationContext is just a BeanFactory BeanFactory factory = (BeanFactory) context;
方法6
InputStream is = new FileInputStream("beans.xml"); BeanFactory factory = new XmlBeanFactory(is);
方法7
ClassPathResource res = new ClassPathResource("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(res);
方法8
ApplicationContext ac = new FileSystemXmlApplicationContext ("C:/SpringConfig/Spring-Config.xml");
方法9 :多个xml文件导入到一个xml中进行加载
将XML配置文件分拆成多个部分是非常有用的。为了加载多个XML文件生成一个ApplicationContext实例,可以将文件路径作为 字符串数组传给 ApplicationContext构造器。而bean factory将通过调用bean defintion reader从多个文件中读取bean定义。
通常情况下,Spring团队倾向于上述做法,因为这样各个配置并不会查觉到它们与其他配置文件的组合。另外一种方法是使用一个或多个的<import/> 元素来从另外一个或多个文件加载bean定义。所有的<import/>元素必须放在<bean/>元素之前以完成bean定义的导入。 让我们看个例子:
<beans><import resource="services.xml"/> <import resource="resources/messageSource.xml"/> <import resource="/resources/themeSource.xml"/> <bean id="bean1" class="..."/> <bean id="bean2" class="..."/> </beans>
在上面的例子中,我们从3个外部文件:services.xml、messageSource.xml及themeSource.xml来加载bean定义。这里采用的都是相对路径,因此,此 例中的services.xml一定要与导入文件放在同一目录或类路径,而messageSource.xml和themeSource.xml的文件位置必须放在导入文件所在目录下的 resources目录中。正如你所看到的那样,开头的斜杠‘/’实际上可忽略。因此不用斜杠‘/’可能会更好一点。
根据Spring XML配置文件的Schema(或DTD),被导入文件必须是完全有效的XML bean定义文件,且根节点必须为<beans/> 元素。
加载文件时候通配符使用 (Ant-style Patterns)
classpath*:conf/appContext.xml 搜索所有的类路径中的conf/appContext.xml文件(包括src和jar文件中)
classpath:com/mycompany/**/service-context.xml 以com/mycompany为跟路径来查找 文件所在
例子:
/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
加载文件前缀的使用:
Prefix | Example | Explanation |
classpath: 会用 ClassPathResource 加载 | classpath:com/myapp/config.xml | Loaded from the classpath. |
file: 会用UrlResource加载 | file:/data/config.xm | Loaded as a URL, from the filesystem. |
http: | http://myserver/logo.png | Loaded as a URL. |
none | /data/config.xml | Depends on the underlying ApplicationContext. |