自动装配

使用类型注释完成自动装配,以指定 ApplicationContext 中将成为 bean 的类,并使用 AutowiredValue 注释指定 bean 依赖项。自动装配的独特之处在于没有外部的 ApplicationContext 定义,因为它都是在 bean 本身的类中完成的。

@Component // The annotation that specifies to include this as a bean
           // in the ApplicationContext
class Book {
    
    @Autowired // The annotation that wires the below defined Author
               // instance into this bean
    Author author;

    String title = "It";

    Author getAuthor() { return author; }
    String getTitle() { return title; }
}

@Component // The annotation that specifies to include
           // this as a bean in the ApplicationContext
class Author {
    String firstName = "Steven";
    String lastName = "King";

    String getFirstName() { return firstName; }
    String getLastName() { return lastName; }
}