首页 > 代码库 > Spring系列【7】零配置实现Bean的注入

Spring系列【7】零配置实现Bean的注入

与前几例不同,需要导入aop包。

Book.java 注意Book类@Component

 1 package cn.com.xf; 2  3 import org.springframework.stereotype.Component; 4  5 @Component 6 public class Book { 7     private String name="JAVA从入门到精通"; 8     private double price=45.67; 9     public String getName() {10         return name;11     }12     @Override13     public String toString() {14         return "Book [name=" + name + ", price=" + price + "]";15     }16     public void setName(String name) {17         this.name = name;18     }19     public double getPrice() {20         return price;21     }22     public void setPrice(double price) {23         this.price = price;24     }25 }

Person.java Person类@Component

 1 package cn.com.xf; 2  3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Component; 5  6 @Component 7 public class Person { 8     private String address="河南省南阳市"; 9     @Autowired10     private Book book;11     public String getAddress() {12         return address;13     }14     @Override15     public String toString() {16         return "Person [address=" + address + ", book=" + book + "]";17     }18     public void setAddress(String address) {19         this.address = address;20     }21     public Book getBook() {22         return book;23     }24     public void setBook(Book book) {25         this.book = book;26     }27 }

Spring配置文件:注意<context:annotation-config/>

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="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-scan base-package="cn.com.xf"> 9     </context:component-scan>10 </beans>

Spring系列【7】零配置实现Bean的注入