一.Spring中applicationContext.xml配置bean的两种加载方式
<bean id="student" class="com.xlc.ioc.Student">
<property name="name" >
<value>旺财</value>
</property>
</bean>
</beans>
package com.xlc.ioc;
public class Student {
private String name;
public Student(){
System.out.println("Student创建");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
1.加载到applicationContext上下文容器中获取bean
ApplicationContext ac =new ClassPathXmlApplicationContext("com/xlc/ioc/beans.xml");
ac.getBean("student");
2.使用bean工厂容器中获取bean
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("com/xlc/ioc/beans.xml"));
beanFactory.getBean("student");
两则都是利用反射机制实例化
二.两者获取bean的区别
<pre name="code" class="java">ApplicationContext ac =new ClassPathXmlApplicationContext("com/xlc/ioc/beans.xml");
这句话执行时在ApplicationContext容器中New了下,并且执行了bean中默认的无参构造方法
public Student(){
System.out.println("Student创建");
}
当我们实例化beans.xml时,该文件中配置的bean被加载到内存实例化()
而bean工厂方式获取bean,只在Getbean()方法调用时,才会实例化bean(延迟加载)
可以类似于单例模式中懒汉式(beanFactory)与饿汉式(applicationContext上下文容器)
三种获取ApplicationContext 对象引用的方法
1. ClassPathXmlApplicationContext-> 通过类路径
2. FileSystemXmlApplicationContext-> 通过文件路径
举例:
ApplicationContext ac=newFileSystemXmlApplicationContext("文件路径beans.xml / applicationContext.xml");
3. XmlWebApplicationContext:从web系统中加载
<pre name="code" class="java">ApplicationContext ac =
<span style="white-space:pre"> </span>new ClassPathXmlApplicationContext("com/xlc/ioc/beans.xml");
ApplicationContext context =
new FileSystemXmlApplicationContext("c:\
beans
.xml");
ApplicationContext context = new ClassPathXmlApplicationContext(" beans .xml ");