说说FactoryBean

本文深入探讨了Spring框架中FactoryBean的作用与实现方式,通过具体示例展示了如何利用FactoryBean简化XML配置,并实现了根据配置生成不同类型Bean的功能,进一步提高了代码的灵活性与可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在前面

FactoryBean有什么作用:

FactoryBean是以工厂形式生成Bean,在对Bean进行修饰之后返回Bean。

常用的使用场景为: 根据不同的配置类型返回不同类型的处理Bean,整体上简化了XML配置等。

Spring本身有70多个FactoryBean的实现,通过它隐藏了一些复杂的实现细节。

理解FactoryBean

举个例子,看看通过FactoryBean简化XML配置。

public class Student {
	/** 姓名 */
	private String name;
	/** 年龄 */
	private int age;
	/** 班级名称 */
	private String className;
}

实现FactoryBeen接口:

public class StudentFactoryBean implements FactoryBean<Student> {

	private String studentInfo;

	@Override
	public Student getObject() throws Exception {
		if (this.studentInfo == null) {
			throw new IllegalArgumentException("'studentInfo' is required");
		}

		String[] splitStudentInfo = studentInfo.split(",");
		if (null == splitStudentInfo || splitStudentInfo.length != 3) {
			throw new IllegalArgumentException("'studentInfo' config error");
		}

		Student student = new Student();
		student.setName(splitStudentInfo[0]);
		student.setAge(Integer.valueOf(splitStudentInfo[1]));
		student.setClassName(splitStudentInfo[2]);
		return student;
	}

	@Override
	public Class<?> getObjectType() {
		return Student.class;
	}

	public void setStudentInfo(String studentInfo) {
		this.studentInfo = studentInfo;
	}
}

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

	<!--注意:class不是Student而是StudentFactoryBean-->
	<bean id="student" class="com.lyc.cn.day03.StudentFactoryBean" p:studentInfo="张三,25,三年二班"/>

</beans>

测试:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("day03.xml");
System.out.println(applicationContext.getBean("student"));
System.out.println(applicationContext.getBean("&student"));
		
Student{name='张三', age=25, className='三年二班'}
org.springframework.beans.factory_bean.StudentFactoryBean@1ae369b7

这样就简化了通过BeanFactory接口简化配置XML的作业了。如果不加&返回的是实例,加了返回的是工厂bean本身。

默认返回单例:

    //实例是否单例模式,默认返回true
	default boolean isSingleton() {
		return true;
	}

实现个性化输出Bean

通过FactoryBean个性化输出Bean。

public interface Animal {
	void sayHello();
}
public class Cat implements Animal {
	@Override
	public void sayHello() {
		System.out.println("hello, 喵喵喵...");
	}
}
public class Dog implements Animal {
	@Override
	public void sayHello() {
		System.out.println("hello, 汪汪汪...");
	}
}

对于Animal 接口有两个实现:Cat和Dog。

新建AnimalFactorybean:

public class AnimalFactoryBean implements FactoryBean<Animal> {

	private String animal;

	@Override
	public Animal getObject() throws Exception {
		if (null == animal) {
			throw new IllegalArgumentException("'animal' is required");
		}
		if ("cat".equals(animal)) {
			return new Cat();
		} else if ("dog".equals(animal)) {
			return new Dog();
		} else {
			throw new IllegalArgumentException("animal type error");
		}
	}

	@Override
	public Class<?> getObjectType() {
		if (null == animal) {
			throw new IllegalArgumentException("'animal' is required");
		}
		if ("cat".equals(animal)) {
			return Cat.class;
		} else if ("dog".equals(animal)) {
			return Dog.class;
		} else {
			throw new IllegalArgumentException("animal type error");
		}
	}

	public void setAnimal(String animal) {
		this.animal = animal;
	}
}

增加XML配置:

<bean id="animal" class="com.lyc.cn.day03.AnimalFactoryBean" p:animal="cat"/>

测试:

public void testAnimalFactoryBean() {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("day03.xml");
	Animal animal = applicationContext.getBean("animal", Animal.class);
	animal.sayHello();
}
--------------------- 
hello, 喵喵喵...

转载于:https://my.oschina.net/u/1000241/blog/3073950

FactoryBean是Spring框架提供的一个接口,用于生成Bean实例的工厂。它允许我们在创建Bean实例时进行一些自定义的逻辑处理。FactoryBean接口有两个关键方法:getObject()和getObjectType()。 getObject()方法用于返回一个由FactoryBean创建的Bean实例,这个方法可以在每次调用时返回一个新的实例,也可以返回同一个实例。 getObjectType()方法用于返回由FactoryBean创建的Bean实例的类型。这个方法在Spring容器需要自动注入Bean时会被用到。 使用FactoryBean可以实现一些特殊的功能,例如延迟初始化、条件创建、动态代理等。我们可以通过在配置文件中使用<bean>标签,并指定FactoryBean的实现类来创建Bean实例。 例如,以下是一个使用FactoryBean创建Bean的示例: ```java public class MyFactoryBean implements FactoryBean<MyBean> { @Override public MyBean getObject() throws Exception { // 创建并返回MyBean实例 return new MyBean(); } @Override public Class<MyBean> getObjectType() { return MyBean.class; } @Override public boolean isSingleton() { return true; // 返回true表示单例模式,返回false表示原型模式 } } // 在配置文件中使用FactoryBean <bean id="myBean" class="com.example.MyFactoryBean" /> ``` 在上面的示例中,通过配置文件中的<bean>标签指定了MyFactoryBean类作为创建myBean实例的工厂。当需要获取myBean实例时,Spring容器会调用MyFactoryBean的getObject()方法返回一个MyBean实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值