ITeye博客

spring2.5学习笔记(五):spring自动扫描和管理Bean

sfwhhp · 2010-09-17 21:09 · spring2.5 · 企业架构 · junit · Spring · 项目管理 · 配置管理 · Bean · Markdown

当我们使用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取值

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。