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!