1. 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
    1. - FactoryBean对象
    2. ```java
    3. public class AuthorFactoryBean implements FactoryBean<Author> {
    4. @Override
    5. public Author getObject() throws Exception {
    6. Author author = new Author();
    7. author.setAge(10);
    8. author.setName("高溪");
    9. return author;
    10. }
    11. @Override
    12. public Class<?> getObjectType() {
    13. return Author.class;
    14. }
    15. @Override
    16. public boolean isSingleton() {
    17. return true;
    18. }
    19. }
    • 被FactoryBean创建的对象 ```java public class Author {

      private String name;

      private Integer age;

    1. public void setName(String name) {
    2. this.name = name;
    3. }
    4. public void setAge(Integer age) {
    5. this.age = age;
    6. }
    7. @Override
    8. public String toString() {
    9. return "Author{" +
    10. "name='" + name + '\'' +
    11. ", age=" + age +
    12. '}';
    13. }

    }

    1. - 启动类
    2. ```java
    3. /**
    4. * 各种类型的注入方式
    5. */
    6. @Test
    7. public void testAllType() {
    8. ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");
    9. Author bean = applicationContext.getBean(Author.class);
    10. System.out.println(bean);
    11. //通过name获取的是Author
    12. Object authorFactoryBean = applicationContext.getBean("authorFactoryBean");
    13. System.out.println(authorFactoryBean);
    14. //获取自身
    15. AuthorFactoryBean self = (AuthorFactoryBean) applicationContext.getBean("&authorFactoryBean");
    16. System.out.println(self.isSingleton());
    17. }