在使用beans.xml文件配置容器管理的bean时,即使使用了注解方式来对bean属性进行装配的情况下,如果容器需要管理的bean太多,也会造成beans.xml文件的臃肿,所以spring提供了自动扫描及管理bean的方法。

 

要使用自动扫描功能,需要在配置文件中加入以下代码:


Java代码



<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    <!-- 引入 context 命名空间 -->  
    xmlns:context = "http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    <!-- 加入 context scheme文件 -->  
    http://www.springframework.org/schema/context   
http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
       <!-- 打开自动扫描功能 自动扫描功能已经提供了注解功能所需要的处理器,所以不再需要配置打开注解功能(<context:annotation-config/>) -->
       <context:component-scan base-package="com.risetek"/> 
       ......   
</beans>

 经过上述配置后,在spring容器实例化的时候,容器会自动扫描“com.risetek”包下的所有类,我们只要在需要被容器管理的类上加上一个注解,容器就会将该类纳入容器进行管理了,而表示该类需要被容器管理的注解有以下几种:

   @Component :表示该类是一个通用的Bean
   @Service :表示该类是一个服务层的Bean
   @Controller :表示该类是一个控制层的Bean
   @Repository :表示该类是一个数据访问层的Bean

以上四种形式的注解都将会告诉spring容器,该类需要被容器管理,目前版本的spring对四种注解类型并没有做特殊的处理,四种注解的使用效果都是一样

 

下面以@Componet为例,如何使用注解标识需要被管理的类:

    PersonDaoImpl.java


Java代码

//括号中的字符串表明该类在容器中的名称,如果不指定名称,则容器中的名称则为该类的简单名称(类名第一个字母小写)
@Component(“personDao”)
public class PersonDaoImpl implements PersonDao {
    ....
}

   PersonServiceBean.java


Java代码

@Component
public class PersonServiceBean implements PersonService {
    //为属性按名称进行装配

	@Resource(name="personDao")
	private PersonDao personDao;
}

 经过配置@Component注解,就将PersonServiceBean和PersonDaoImpl类交给了spring容器管理,在从容器中获取PersonServiceBean实例的时候,容器也会自动将PersonServiceBean中的属性按照@Resource注解方式进行装配。

 

同样也可以通过注解方式设置Bean类的作用域以及初始化、销毁方法


Java代码  

1. @Component
2. @Scope("prototype")    
3. public class PersonServiceBean implements
4.   
5. @Resource
6. private
7.   
8. public
9. "PersonServiceBean....");    
10.     }   
11.        
12. //此方法会在构造方法执行之后执行 
13. @PostConstruct
14. public void
15. "init...");    
16.     }   
17.        
18. //此方法会在对象销毁之前执行 
19. @PreDestroy
20. public void
21. "destory...");    
22.     }   
23. }