---
title: "spring2.5学习笔记（五）：spring自动扫描和管理Bean"
author: "sfwhhp"
date: "2010-09-17T21:09:22Z"
tags: ["Bean", "Spring", "junit", "配置管理", "项目管理"]
categories: ["企业架构"]
slug: "spring2-5-spring-bean"
draft: false
lastmod: "2010-09-27T10:23:11Z"
id: 766232
url: "https://sfwhhp.iteye.com/blog/766232"
---

当我们使用xml的bean标签来配置组件时，如果遇到很大的项目会有成百上千个组件，那可以想象，xml文件体积是多么的庞大，维护起来也不太方便。spring2.5引入了组件的自动扫描机制，它可以在类路径需找标注了@Service,@Repository,@Controller,@Component这四个注解的类，来加以自动管理。 第一步： beans2.xml \[code="xml"] \[/code] base-package="cn.itcast"说明了要扫描的包（包括子包） 以下三句是使用spring自动管理bean必不可少的： xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 第二步：定义的接口IPersonService，和接口实现，以及业务实现类PersonServiceBean2 \[code="java"] package cn.itcast.service; public interface IPersonService { } \[/code] \[code="java"] package cn.itcast.dao.impl; public interface IPersonDao { public abstract void add(); } package cn.itcast.dao.impl; import org.springframework.stereotype.Repository; @Repository("persondao") public class PersonDaoBean implements IPersonDao { public void add(){ System.out.println("执行PersonDaoBean类中的add方法"); } } \[/code] \[code="java"] package cn.itcast.service.impl; import cn.itcast.service.IPersonService; @Service("personService\_zidong") public class PersonServiceBean2 implements IPersonService { private IPersonDao iPersonDao; public void save() { iPersonDao.add(); } } \[/code] 在这里运用的@Service("personService\_zidong")，就相当于，在配置文件里面做了这样的配置： 测试类： \[code="java"] package junit.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.service.IPersonService; public class springTest2 { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans2.xml"); IPersonService ipersonService2 = (IPersonService)ac.getBean("personService\_zidong"); ipersonService2.save(); } } \[/code] 学习感想： 1：@Service,@Repository,@Controller,@Component四个注解的区别，还有待研究 2：这样spring自动管理后，如果要得到某个类的Bean直接上类头上面看就是了，@Service("personService\_zidong") ，里面的personService\_zidong就是bean的id取值