相关测试类
public class User { public User() { System.out.println("User构造方法执行了"); } public void info(){ System.out.println("user"); } } @Component public class TestFactoryBean implements FactoryBean { public TestFactoryBean() { System.out.println("TestFactoryBean构造方法执行了"); } public void test(){ System.out.println("test"); } public Object getObject() throws Exception { return new User(); } public Class<?> getObjectType() { return TestFactoryBean.class; } public boolean isSingleton() { return true; } } @Configuration @ComponentScan("com.liaoxiang") public class AppConfig { } public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); TestFactoryBean testFactoryBean = (TestFactoryBean)ac.getBean("testFactoryBean"); testFactoryBean.test(); } }执行结果:
修改测试方法
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); User user = (User)ac.getBean("testFactoryBean"); user.info(); } }可以看到通过ac.getBean("testFactoryBean")得到的Bean并不是TestFactoryBean的实例对象,而是User对象。即ac.getBean("testFactoryBean")获取得到的Bean是TestFactoryBean中getObject()方法实际返回的Bean,如果想要获取TestFactoryBean的实例对象,可以通过下面的方式
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); TestFactoryBean testFactoryBean = (TestFactoryBean)ac.getBean("&testFactoryBean"); testFactoryBean.test(); } }