spring Autowiring


Example

Autowiring is done using a sterotype annotation to specify what classes are going to be beans in the ApplicationContext, and using the Autowired and Value annotations to specify bean dependencies. The unique part of autowiring is that there is no external ApplicationContext definition, as it is all done within the classes that are the beans themselves.

@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; }
}