一、工厂方法创建bean对象
1、通过静态工厂方式创建bean对象
<bean id="标识符" class="创建bean对象的工厂类的全类名" factory-method="指向静态工厂方法的方法名"></bean>
2、通过实例工厂方式创建Bean对象
<!-- 1.创建bean对象的工厂类的实例-->
<bean id="标识符" class="创建bean对象的工厂类的全类名"></bean>
<!--2.创建需要的实例对象-->
<bean id="标识符" factory-bean="指向实例工厂对象的标识符" factory-method="实例工厂方法名"></bean>
二、 通过FactoryBean创建对象
Dept.java:
public class Dept {
private Integer deptId;
private String deptName;
public Dept() {
}
public Dept(Integer deptId, String deptName) {
this.deptId = deptId;
this.deptName = deptName;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Dept{" +
"deptId=" + deptId +
", deptName='" + deptName + '\'' +
'}';
}
}
继承了FactoryBean接口的factoryBean:
import org.springframework.beans.factory.FactoryBean;
/* 自定义的factoryBean需要实现FactoryBean接口 */
public class DeptFactoryBean implements FactoryBean {
private int deptId;
public void setDeptId(int deptId) {
this.deptId = deptId;
}
//返回Bean对象
@Override
public Object getObject() throws Exception {
return new Dept(deptId,"市场部");
}
//返回Bean的类型
@Override
public Class<?> getObjectType() {
return Dept.class;
}
//是否单例
@Override
public boolean isSingleton() {
return true;
}
}
xml配置文件中的配置(applicationContext-factoryBean.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">
<!--通过factoryBean创建实例对象
class:指向FactoryBean的全类名
property标签:配置FactoryBean的属性。但是实际返回的实例对象确是FactoryBean的getObject()方法返回的实例对象
-->
<bean id="dept" class="com.zm.bean.factoryBean.DeptFactoryBean">
<property name="deptId" value="1001"/>
</bean>
</beans>
测试方法:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-factoryBean.xml");
Dept dept = (Dept) context.getBean("dept");
System.out.println(dept);
}
运行结果: