spring:继承接口FactoryBean获取bean实例
spring框架提供接口FactoryBean获取bean实例。
实现步骤:
实现接口FactoryBean。
在xml文件中配置实现接口FactoryBean的类。
调用接口FactoryBean中方法getObject,获取bean实例。
实现接口类
package com.itheima.factory;import org.springframework.beans.factory.FactoryBean;import com.itheima.dao.interfaces.InterfaceUserDao;
import com.itheima.dao.impl.UserDaoImpl;/*** @copyright 2003-2024* @author qiao wei* @date 2024-12-24* @version 1.0* @brief 继承接口FactoryBean。通过方法getBean获取Bean,时是延迟调用。* @history name* date* brief*/
public class MyBeanFactory03 implements FactoryBean<InterfaceUserDao> {public MyBeanFactory03() {}@Overridepublic InterfaceUserDao getObject() throws Exception {System.out.println("继承接口FactoryBean");return new UserDaoImpl();}@Overridepublic Class<?> getObjectType() {return null;}@Overridepublic boolean isSingleton() {return FactoryBean.super.isSingleton();}
}
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"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsd"><!-- --><bean id="myUserDao03"class="com.itheima.factory.MyBeanFactory03"></bean>
</beans>
测试调用
package com.itheima.factory;import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.itheima.dao.interfaces.InterfaceUserDao;/*** @copyright 2003-2025* @author qiao wei* @date 2025-04-05* @version 1.0* @brief 继承接口FactoryBean。在读取配置文件时不创建Bean实例。在调用方法getBean时才创建Bean实例并返回。* @history name* date* brief*/
class MyBeanFactory03Test {@Testpublic void test01() {// 读取配置文件,创建容器,未创建Bean实例。ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("/xml/factory/myBeanFactory03.xml");// 通过方法getBean获取Bean实例时,才创建Bean实例。InterfaceUserDao userDao = (InterfaceUserDao) context.getBean("myUserDao03");userDao.print();}
}