您的位置:首页 > 编程语言 > Java开发

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

2014-12-14 22:09 411 查看


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

Book.java 注意Book类@Component

package cn.com.xf;

import org.springframework.stereotype.Component;

@Component
public class Book {
private String name="JAVA从入门到精通";
private double price=45.67;
public String getName() {
return name;
}
@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}


Person.java Person类@Component

package cn.com.xf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Person {
private String address="河南省南阳市";
@Autowired
private Book book;
public String getAddress() {
return address;
}
@Override
public String toString() {
return "Person [address=" + address + ", book=" + book + "]";
}
public void setAddress(String address) {
this.address = address;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
}


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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:annotation-config/>
<context:component-scan base-package="cn.com.xf">
</context:component-scan>
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐