ApplicationContext——ClassPathXmlApplication(一)

       如果说BeanFactory是Spring的心脏,那么ApplicationContext就是完整的身躯了。ApplicationContext由BeanFactory派生而来,提供了更多面向实际应用的功能。在BeanFactory中,很多功能需要以编程的方式实现,而在ApplicationContext中则可以通过配置的方式实现。

一、ApplicationContext

       ApplicationContext的主要实现类是ClassPathXmlApplication和FileSystemXmlApplicationContext,前者默认从类路径中加载配置文件,后者默认从文件系统中装载配置文件。

      与BeanFactory初始化相似,ApplicationContext的初始化也很简单,如果配置文件在类路径下,用户可以优先使用ClassPathXmlApplication实现类:

1、ClassPathXmlApplication:从类路径中加载配置文件

(1)实现类——Car.java文件:

public class Car {
	private String brand;
	private String color;
	private int maxSpeed;
	public Car(){
		
	}
	
	public Car(String brand, String color, int maxSpeed) {
		super();
		this.brand = brand;
		this.color = color;
		this.maxSpeed = maxSpeed;
	}

	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getMaxSpeed() {
		return maxSpeed;
	}
	public void setMaxSpeed(int maxSpeed) {
		this.maxSpeed = maxSpeed;
	}
	@Override
	public String toString() {
		return "brand:"+brand+"  color:"+color+"  maxSpeed:"+maxSpeed;
	}
}

(2)Bean配置文件——beans.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
	<bean id="car1" class="com.bean.Car"
		p:brand="宝马"
		p:color="黑色"
		p:maxSpeed="200"/>
</beans>

(3)Spring IoC容器

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 
 * @author huamanxi
 * ClassPathXmlApplicationContext类
 */
public class ClassPath {
	@Test
	public void testClassPath(){
		ApplicationContext ac=new ClassPathXmlApplicationContext("com/bean/beanfactory/beans.xml");
		System.out.println("init ApplicationContext");
		Car car=(Car) ac.getBean("car1");
		System.out.println(car);
		System.out.println("Car bean is ready for use");
	}
}
注意:别忘了 log4j.properties文件

运行结果:

init ApplicationContext
brand:宝马  color:黑色  maxSpeed:200
Car bean is ready for use

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值