本文主要是介绍Spring -> IOCxml配置bean注入对象为另一个类的对象(FactoryBean)--附加多实例的配置注入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.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"><!--如果需要创建多个对象,不想设置很多条,可以使用scope="prototype"设置为多实例的--><bean id="factoryBeanClass" class="test10month.test1012.FactoryBeanClass" scope="prototype"></bean>
</beans>
2.类
/*** Object getObject():强制返回,配置注入的bean返回为Object;*/
class FactoryBeanClass implements FactoryBean {/*** 使得配置注入的bean更改为Object类型,不是FactoryBeanClass类型*/@Overridepublic Object getObject() throws Exception {return null;}@Overridepublic Class<?> getObjectType() {return null;}@Overridepublic boolean isSingleton() {return false;}
}
3.测试类
package test10month.test1012;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 功能描述:* @version 1.0* @className FactoryBeanTest* @author: 罗德* @create: 2020-10-12 11:52*/
public class FactoryBeanTest {@Testpublic void test() {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10month/test1012/FactoryBeanTestSpring.xml");/*** 改变注入bean的对象为Object*/var factoryBeanClass = context.getBean("factoryBeanClass", Object.class);//多实例:他们的地址是不一样的var factoryBeanClass2 = context.getBean("factoryBeanClass", Object.class);var factoryBeanClass3 = context.getBean("factoryBeanClass", Object.class);System.out.println(factoryBeanClass);}
}
这篇关于Spring -> IOCxml配置bean注入对象为另一个类的对象(FactoryBean)--附加多实例的配置注入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!