- public class SimpleFactoryBean implements FactoryBean {
- private boolean flag;
-
- public Object getObject() throws Exception {
- if (flag) {
- return new Date();
- }
- return new String("false");
- }
-
- @SuppressWarnings("unchecked")
- public Class getObjectType() {
- return flag ? Date.class : String.class;
- }
-
- public boolean isSingleton() {
- return false;
- }
-
- public void setFlag(boolean flag) {
- this.flag = flag;
- }
- }
-
- <bean id="factoryBeanOne" class="com.study.demo.factorybean.SimpleFactoryBean" >
- <property name="flag">
- <value>true</value>
- </property>
- </bean>
-
- <bean id="factoryBeanTwo" class="com.study.demo.factorybean.SimpleFactoryBean" >
- <property name="flag">
- <value>false</value>
- </property>
- </bean>
-
- public class MainTest {
- public static void main(String[] args) {
- Resource res = new ClassPathResource("bean.xml");
- BeanFactory factory = new XmlBeanFactory(res);
- System.out.println(factory.getBean("factoryBeanOne").getClass());
- System.out.println(factory.getBean("factoryBeanTwo").getClass());
- }
- }
通过简单的测试可知,该类输出如下:
class java.util.Date
class java.lang.String
也就是说,容器通过getBean方法返回的不是FactoryBean本身,而是FactoryBean实现类中getObject()方法所返回的对象。