博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring的自动扫描与管理
阅读量:4563 次
发布时间:2019-06-08

本文共 1474 字,大约阅读时间需要 4 分钟。

通过在classpath自动扫描方式把组件纳入spring容器中管理

前面的例子我们都是使用XML的bean定义来配置组件。在一个稍大的项目中,通常会有上百个组件,如果这些这组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找及维护起来也不太方便。spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,我们需要打开以下配置信息:

<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="cn.itcast"/>   默认注册了注解处理器

</beans>

其中base-package为需要扫描的包(含子包)。

 

@Service用于标注业务层组件、 @Controller用于标注控制层组件(如struts中的action)、@Repository用于标注数据访问组件,即DAO组件。而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

 

@Service("personServiceImpl") public class PersonServiceImpl implements PersonService {	@Resource	private PersonDao personDao;		@PostConstruct	public void init(){		System.out.println("init");	}	@PreDestroy	public void destroy(){		System.out.println("destroy");	}	public void save() {		personDao.save();		System.out.println("service层的 save方法");	}			public void setPersonDao(PersonDao personDao) {		this.personDao = personDao;	}	public PersonDao getPersonDao() {		return personDao;	}}

  

 

转载于:https://www.cnblogs.com/E-star/p/3560124.html

你可能感兴趣的文章
json.dumps python错误:'utf8' codec can't decode byte 0xe1 in position 5 解决方案
查看>>
P2505 [HAOI2012]道路
查看>>
wxs旅游增强
查看>>
HDOJ 1091
查看>>
STL排序算法
查看>>
增长率超 100%!东软数据可视化到底什么样?
查看>>
JSP表单提交中文乱码
查看>>
GoF23种设计模式之行为型模式之责任链模式
查看>>
拨号进入防盗界面
查看>>
makefile学习经验(二)----编译生成静态库文件
查看>>
python装饰器
查看>>
HDUOJ---2082
查看>>
【2018.2.8-】网络流学习笔记(含ISAP!)
查看>>
【2019.3.2】NOI 模拟赛
查看>>
设计模式(3)----工厂方法模式
查看>>
Asp.net mvc + .net ef database first 或 model first 时如何添加验证特性
查看>>
Caused by: java.lang.ClassNotFoundException: HttpServletRequest
查看>>
C++primer plus第十章第5题
查看>>
SqlServer 之 查看表空间
查看>>
Python学习笔记(matplotlib篇)--使用matplotlib绘制直方图
查看>>