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对象```javapublic class AuthorFactoryBean implements FactoryBean<Author> {@Overridepublic Author getObject() throws Exception {Author author = new Author();author.setAge(10);author.setName("高溪");return author;}@Overridepublic Class<?> getObjectType() {return Author.class;}@Overridepublic 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;}@Overridepublic String toString() {return "Author{" +"name='" + name + '\'' +", age=" + age +'}';}
}
- 启动类```java/*** 各种类型的注入方式*/@Testpublic void testAllType() {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");Author bean = applicationContext.getBean(Author.class);System.out.println(bean);//通过name获取的是AuthorObject authorFactoryBean = applicationContext.getBean("authorFactoryBean");System.out.println(authorFactoryBean);//获取自身AuthorFactoryBean self = (AuthorFactoryBean) applicationContext.getBean("&authorFactoryBean");System.out.println(self.isSingleton());}
