Spring4使用FactoryBean配置bean

beans-factorybeans.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="car" class="com.atguigu.spring.beans.factorybean.CarFactoryBean">
   </bean>
</beans>

CarFactoryBean.java

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

public class CarFactoryBean implements FactoryBean<Car> {
	
	//返回bean的对象
	@Override
	public Car getObject() throws Exception {
		// TODO Auto-generated method stub
		return new Car("BMW",5000000);
	}

	//返回bean类型
	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return Car.class;
	}

	
	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}

Main.java

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

public class Main {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factorybean.xml");
		Car car =(Car) ctx.getBean("car");
		System.out.println();
		System.out.println(car);
	}

}


你可能感兴趣的:(Spring4使用FactoryBean配置bean)