FactoryBean是一个Bean,但是这个bean的特殊之处在于他创建的不是自己,而是别的bean。<br />如果将其注入后可以使用`&+id`的方式取出自己。[https://gitee.com/gao_xi/spring-demo1/tree/factory-bean/](https://gitee.com/gao_xi/spring-demo1/tree/factory-bean/)
- XML配置
```xml
- FactoryBean对象
```java
public class AuthorFactoryBean implements FactoryBean<Author> {
@Override
public Author getObject() throws Exception {
Author author = new Author();
author.setAge(10);
author.setName("高溪");
return author;
}
@Override
public Class<?> getObjectType() {
return Author.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
被FactoryBean创建的对象 ```java public class Author {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 启动类
```java
/**
* 各种类型的注入方式
*/
@Test
public void testAllType() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");
Author bean = applicationContext.getBean(Author.class);
System.out.println(bean);
//通过name获取的是Author
Object authorFactoryBean = applicationContext.getBean("authorFactoryBean");
System.out.println(authorFactoryBean);
//获取自身
AuthorFactoryBean self = (AuthorFactoryBean) applicationContext.getBean("&authorFactoryBean");
System.out.println(self.isSingleton());
}