BeanFactory is the most basic container of IOC, responsible for producing and managing beans, and it provides the most basic specifications for other specific IOCs. For example, specific containers such as ApplicationContext all implement BeanFactory, and then add other functions to it.
FactoryBean is an interface. When the bean in the IOC container implements FactoryBean, the bean object obtained through getBean(String beanName) is not the implementation class object of FactoryBean, but the object returned by the getObject() method in the implementation class. . To get the implementation class of FactoryBean, getBean(&BeanName), add & before BeanName.
FactoryBean can be said to provide a more flexible configuration for the implementation of beans in the IOC container, which is equivalent to adding a simple factory pattern and decoration pattern. It can be flexibly configured in the getObject() method.
public class FactoryBeanPojo implements FactoryBean{ private String type; @Override public Object getObject() throws Exception { if ("student".equals(type)){ return new Student(); }else { return new School(); } } @Override public Class<?> getObjectType() { return School.class; } @Override public boolean isSingleton() { return true; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
public class Application { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-first.xml"); //Test factoryBean interface Object school = context.getBean("factoryBeanPojo"); FactoryBeanPojo factoryBeanPojo = (FactoryBeanPojo) context.getBean("&factoryBeanPojo"); System.out.println(school.getClass().getName()); System.out.println(factoryBeanPojo.getClass().getName()); } }