spring编码方式实例化bean
一般情况下,Spring通过反射机制利用<bean>的class属性指定的实现类实例化bean,也可以通过java类或注解的方式实例化bean。
Spring还也提供了编码方式实例化bean。Spring为此提供了一个org.springframework.beans.factory.FactoryBean工厂类接口,可以通过实现该接口来实例化bean。org.springframework.beans.factory.FactoryBean接口对于Spring框架来说占有重要的地位,Spring自身就提供了70多个FactoryBean的实现类。
提示:在Spring中BeanFactory和FactoryBean是两个不同的接口
Demo
import org.springframework.beans.factory.FactoryBean; public class CarFactoryBean implements FactoryBean<Car> { private String carInfo; public String getCarInfo() { return carInfo; } public void setCarInfo(String carInfo) { this.carInfo = carInfo; } /** * 将来调用getBean()方法返回的不是FactoryBean本身,而是getObject返回的Car * 也就是说下面这个getObjext方法会被getBean方法代理 */ public Car getObject() { Car car = new Car(); String[] infos = carInfo.split(","); car.setBrand(infos[0]); car.setMaxSpeed(Integer.parseInt(infos[1])); car.setPrice(Double.parseDouble(infos[2])); return car; } @Override public Class<?> getObjectType() { return Car.class; } @Override public boolean isSingleton() { return false; } } class Car { private String brand; private int maxSpeed; private double price; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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="CarFactoryBean" p:carInfo="吉利博越,200,10000.50"/> </beans>
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Driver { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("my.xml"); /** * 当调用getBean("car")时,Spring通过反射机制发现CarFactoryBean实现了FactoryBean的接口, * Spring容器就调用CarFactoryBean的getObject返回Car对象 */ Car car = context.getBean("car", Car.class); System.out.println(car.getBrand()); /** * 如果希望获得CarFactoryBean的实例,需要在加前缀 & */ CarFactoryBean carFactoryBean = context.getBean("&car", CarFactoryBean.class); System.out.println(carFactoryBean); } }
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.16.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.16.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.16.RELEASE</version> </dependency>