package com.spring.bean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;
@Component
public class FacotryBeanDemo implements FactoryBean {
@Override
public Object getObject() throws Exception {
return new Student();
}
@Override
public Class<?> getObjectType() {
return Student.class;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
package com.spring.bean;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Data
public class Student extends Person {
private String name;
private int age;
@Override
public String show(String str) {
System.out.println("Studeng:test()");
return str;
}
}
@org.junit.Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Student bean = (Student)context.getBean("facotryBeanDemo");
FacotryBeanDemo facotryBeanDemo = (FacotryBeanDemo)context.getBean("&facotryBeanDemo");
System.out.println("Student:"+bean);
System.out.println("FacotryBeanDemo:"+facotryBeanDemo);
}
从上面代码可以看出即使student没有注解,也没有通过xml配置,最后也交给了spring管理,这是因为通过factoryBeanDemo将其交给了spring管理,但是其不在单例池中,而是在factoryBeanObjectCache缓存中;
源码如下: