src\dayday\CarFactoryBean.java
package dayday;
import org.springframework.beans.factory.FactoryBean;
/**
* Created by I am master on 2016/11/30.
*/
//自定义的FactoryBean需要实现FactoryBean接口
public class CarFactoryBean implements FactoryBean<Car>{
private String brand;
public void setBrand(String brand){
this.brand=brand;
}
@Override
public Car getObject() throws Exception {
return new Car(brand,"50w");
}
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
src\dayday\Car.java
package dayday;
import com.sun.org.apache.xpath.internal.SourceTree;
import javax.sound.midi.Soundbank;
/**
* Created by I am master on 2016/11/28.
*/
public class Car {
private String name;
private String money;
public void setName(String name){
this.name=name;
System.out.println("setName...");
}
public String getName(){
return name;
}
public void setMoney(String money){
this.money=money;
}
public String getMoney(){
return money;
}
public String toString(){
return "Car"+"["+"carname="+name+" carValue="+money+"]";
}
public Car(String name,String money){
this.money=money;
this.name=name;
}
public Car(){
System.out.println("Car's constructor...");
}
public void init(){
System.out.println("init...");
}
public void destroy(){
System.out.println("destroy...");
}
}
src\dayday\Main.java
package dayday;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
/**
* Created by I am master on 2016/11/28.
*/
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
Car car=ctx.getBean("car",Car.class);
System.out.println(car);
}
}
src\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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--
通过FactoryBean来配置Bean的实例
class指向FactoryBean的全类名
property:配置FactoryBean的属性,但实际返回的实例是FactoryBean的getObject()方法返回的实例
-->
<bean id="car" class="dayday.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
</beans>
运行结果
Car[carname=BMWcarValue=50w]