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

前面的例子我们都是使用xml的bean定义来配置组件,如果组件过多很臃肿。spring2.5引入了组件自动扫描机制,在指定目录下查找标注了@Component、@Service、@Controller、@Repositiory注解的类,并把这些类自动纳入spring容器中管理。


要使用自动扫描机制,我们需要打开以下配置信息:
1、加入context组件,导入注解对应jar:
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

2、打开组件自动扫描:
<context:component-scan base-package="..."/>
base-package属性指定要扫描的package,包括其子package。

如果打开了自动扫描的话,会自动开启一些其他context配置组件,比如前面的:<context:annotation-config/>就可以省略了

@Service用于标注业务层组件、
@Controller用于标注控制层组件、
@Repository用于标注数据访问组件,即DAO组件
@Component泛指所有组件,如果无法判断就使用它
暂时这四个注解没多大区别。

四个组件中都只有一个value属性,表示bean的id属性。默认值为类名的首字母大写

代码片段:
@Repository
public class PersonDaoBean implements PersonDao {

@Service(value="personService")
public class PersonServiceBean implements PersonService {
@Resource(name="personDaoBean")
private PersonDao personDao;

既然可以自动扫描,使用注解形式生成bean了,我们在原来xml中海油一些属性,例如scope属性如何设置呢?
scope属性 @Scope(value="...") 默认值是singleton
初始化方法:@PostConstruct 作用在方法上
销毁方法: @PreDestory 作用在方法上

@PostConstruct
public void init(){

@PreDestroy
public void destory(){

原文地址:https://www.cnblogs.com/aigeileshei/p/5910892.html