当前位置: 首页 > 工具软件 > Go-IOC > 使用案例 >

Spring --- IOC 容器 之 Bean管理XML方式(工厂bean :FactoryBean)

佟云
2023-12-01

    工厂bean的使用,可以实现获取不同于声明实体类的类,前面的文章:Spring — IOC 容器 之 Bean管理XML方式(创建对象) 获取的类即是声明的类,但是当声明的类实现 FactoryBean 接口,即可使得调用方法获取不同的类。下面小编来演示一下,Let go!
1,xml 文件配置:BeanConfig.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">

 <bean id="man" class="com.chaoge.nacos.demo.test.spring.entity.Man">
 </bean>
</beans>

2,上述及下述配置文件所用 Man 实体实现 FactoryBean接口

public class Man implements FactoryBean<User> {
    @Override
    public User getObject() throws Exception {
        User user = new User();
        user.setName("ppkk");
        return user;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

User 实体类:

public class User {

    private String name;
	//set 方法略...
}

3,使用

public class BeanTest {
	@Test
    public void test5(){
        ApplicationContext context = new ClassPathXmlApplicationContext("com/chaoge/nacos/demo/test/spring/beanConfig/BeanConfig.xml");
        //此处,即可获取到 User类型实体
        User user = context.getBean("man", User.class);
        System.out.println(user);
    }
}

输出:

D:\jdk\jdk1.8.0_171\bin\java.exe 
User{name='ppkk'}
 类似资料: