零配置實現Bean注入

下面是 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組件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章