当前位置: 代码迷 >> 综合 >> Spring -> IOCxml配置bean注入对象为另一个类的对象(FactoryBean)--附加多实例的配置注入
  详细解决方案

Spring -> IOCxml配置bean注入对象为另一个类的对象(FactoryBean)--附加多实例的配置注入

热度:91   发布时间:2023-12-16 10:02:29.0

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);}
}
  相关解决方案