Unlike the previous examples, you need to import an AOP package.
Book.java Note Book Class @component
1 Packagecn.com.xf;2 3 Importorg.springframework.stereotype.Component;4 5 @Component6 Public classBook {7 PrivateString name= "Java from getting started to mastering";8 Private Doubleprice=45.67;9 PublicString GetName () {Ten returnname; One } A @Override - PublicString toString () { - return"Book [name=" + name + ", price=" + Price + "]"; the } - Public voidsetName (String name) { - This. Name =name; - } + Public DoubleGetPrice () { - returnPrice ; + } A Public voidSetprice (DoublePrice ) { at This. Price =Price ; - } -}
Person.java Person Class @component
1 Packagecn.com.xf;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 Importorg.springframework.stereotype.Component;5 6 @Component7 Public classPerson {8 PrivateString address= "Nanyang, Henan Province";9 @AutowiredTen PrivateBook book ; One PublicString getaddress () { A returnaddress; - } - @Override the PublicString toString () { - return"Person [address=" + Address + ", book=" + book + "]"; - } - Public voidsetaddress (String address) { + This. Address =address; - } + PublicBook GetBook () { A returnBook ; at } - Public voidSetbook (book book) { - This. Book =Book ; - } -}
Spring configuration file: Note <context:annotation-config/>
1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 Xmlns:context= "Http://www.springframework.org/schema/context"5 xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.1.xsd ">7 <Context:annotation-config/>8 <Context:component-scanBase-package= "CN.COM.XF">9 </Context:component-scan>Ten </Beans>
Spring Series "7" 0 configuration implements Bean injection