Book.java
1 Packagecn.com.xf;2 3 Public classBook {4 PrivateString name;5 Private DoublePrice ;6 PublicString GetName () {7 returnname;8 }9 Public voidsetName (String name) {Ten This. Name =name; One } A @Override - PublicString toString () { - return"Book [name=" + name + ", price=" + Price + "]"; the } - Public DoubleGetPrice () { - returnPrice ; - } + Public voidSetprice (DoublePrice ) { - This. Price =Price ; + } A}
Person.java
Note: @Resource (name= "book") location
1 Packagecn.com.xf;2 3 ImportJavax.annotation.Resource;4 5 Public classPerson {6 PrivateString address;7 @Resource (name= "book")8 PrivateBook book ;9 PublicString getaddress () {Ten returnaddress; One } A Public voidsetaddress (String address) { - This. Address =address; - } the @Override - PublicString toString () { - return"Person [address=" + Address + ", book=" + book + "]"; - } + PublicBook GetBook () { - returnBook ; + } A Public voidSetbook (book book) { at This. Book =Book ; - } -}
Spring configuration file: declaring the Org.springframework.context.annotation.CommonAnnotationBeanPostProcessor class
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <BeanID= "book"class= "Cn.com.xf.Book"> < Propertyname= "Name"value= "Java Series books"></ Property> < Propertyname= "Price"value= "34.56"></ Property> </Bean> <BeanID= "Person"class= "Cn.com.xf.Person"> < Propertyname= "Address"value= "Henan province County"></ Property> </Bean> <Beanclass= "Org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> </Bean></Beans>
Test class: Returns the result correctly.
1 Packagecn.com.xf;2 3 ImportOrg.springframework.context.ConfigurableApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 Public classMaintest {7 8 Public Static voidMain (string[] args) {9Configurableapplicationcontext ctx=NewClasspathxmlapplicationcontext ("Applicationcontext.xml");TenPerson p= (person) ctx.getbean (' person '); One System.out.println (p); A ctx.close (); - } -}
Spring Series "6" @Resource annotations implement bean injection