`

spring容器自动扫面管理bean-学习笔记

阅读更多


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


spring在2.5之后的版本就引入了组件自动扫描机制,它可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,需要打开以下配置信息:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd "
default->
<context:component-scan base-package="com.sample"/>
</beans>
 

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

@Service用于标注业务层组件

@Controller用于标注控制层组件(如struts的action)

@Repository用于标注数据访问层组件、即DAO组件

@Component泛指组件、当组件不好归类的时候,我没可以使用这个注解进行标注


目前Spring只是区分了以上注解,但是在底层没有具体实现上的区分。


注意:

a、我们也可以在注解中指定bean的名字、根据主机指定名字获取bean @Service("personService")

b、我没也可以在注解中指定bean的生成方式,默认为单例,可以指定为原型 

@Service("personService") @Scope("propotype")

c、可以使用注解指定bean的初始化和销毁方法


@PostConstruct  对应bean配置中的init-method

@PreDestroy 对应bean配置中的destroy-method

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics