码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-14 22:32:43      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   sp   java   on   

bubuko.com,布布扣

与前几例不同,需要导入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     @Override
13     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     @Autowired
10     private Book book;
11     public String getAddress() {
12         return address;
13     }
14     @Override
15     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的注入

标签:style   blog   http   io   color   os   sp   java   on   

原文地址:http://www.cnblogs.com/jikoy/p/4163131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!