下面是 XML配置
。
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.lh.*" />
</beans>
之前讲到的@Resourse和@Autowired注入都是要添加在指定的Bean容器中的,但是如果使用<context:component-scan base-package=“com.lh.*” />,组件扫描器他会直接注册到两个容器中,只需要声明是何种组件就可以,这里的就是component组件。
base-package="com.lh." 是指定要扫描的包名*
下面是 book
。
package com.lh.entity;
import org.springframework.stereotype.Component;
@Component
public class Book {
private String bookName ;
private double price;
private String author;
private String bookmaker;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBookmaker() {
return bookmaker;
}
public void setBookmaker(String bookmaker) {
this.bookmaker = bookmaker;
}
}
下面展示一些 bookfactory
。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lh.entity.Book;
@Component
public class TestUtil {
@Autowired
//@Resource(name="book")也是可以的
private Book book;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public boolean getBookInfo(){
if(book!=null){
return true;
}else{
return false;
}
}
}
在book类和bookfactory类中就声明了Component组件。