零配置实现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...
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值