普通的Bean:在配置文件中定义bean类型就是返回类型
FactoryBean:在配置文件中定义bean类型可以和返回类型不一样
package factory;
import org.springframework.beans.factory.FactoryBean;
import pojo.User;
public class Person implements FactoryBean<User> {
//定义返回的Bean
@Override
public User getObject() throws Exception {
User user = new User();
user.setUserName("Tom");
return user;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
<?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="person" class="factory.Person"></bean>
</beans>
import factory.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.User;
public class testSpring {
@Test
public void testPerson() {
//加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("Person.xml");
//获取配置文件创建的对象
User user = context.getBean("person", User.class); //配置文件中定义的bean类型Person,这里返回的是User
System.out.println(user.toString()); //
}
}
版权声明:本文为Archer__13原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。