【Spring】Spring 3.x企业应用开发实战(6)----BeanFactory

BeanFactory是一个类工厂,是类的通用工厂。不多说,直接进入BeanFactory的使用:

首先建一个Bean类,Car.java

 

package com.techman.reflect;

public class Car 
{
	private String brand;
	private String color;
	private int 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;
	}
	
	public Car(){
		
	}
	
	public Car(String brand,String color,int maxSpeed){
		this.brand=brand;
		this.color=color;
		this.maxSpeed=maxSpeed;		
	}
	
	public void introduce()
	{
		System.out.println("Brand is "+brand+" Color is "+color+" Max Speed is "+maxSpeed);
	}
}

配置一个beans.xml文件来指明bean的位置。

 

 

<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<bean id="car1" class="com.techman.reflect.Car" p:brand="宝马X7" p:color="白色" p:maxSpeed="350"/>						
</beans>


然后在类中实现Bean的初始化和调用。

 

BeanFactoryTest.java

 

package com.techman.resource;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.techman.reflect.Car;

public class BeanFactoryTest 
{
	public static void main(String []args)throws Throwable
	{
		ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
		Resource res=resolver.getResource("classpath:com/techman/resource/beans.xml");
		BeanFactory bf=new XmlBeanFactory(res);
		System.out.println("Init BeanFactory.");
		
		Car car=bf.getBean("car1",Car.class);
		
		car.introduce();
		
		System.out.println("Car Bean is ready for use!");
	}
}


结果为:

 

Init BeanFactory.
Brand is 宝马X7 Color is 白色 Max Speed is 350
Car Bean is ready for use!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值