Spring框架初探【2】

一.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 ");

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值