自動裝配

使用型別註釋完成自動裝配,以指定 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; }
}