Spring2.5学习3.4_让Spring自动扫描和管理Bean

来源:互联网 发布:关于网络诈骗的案例 编辑:程序博客网 时间:2024/04/27 18:11

通过在类路径下,根据自动扫描方式,把组件纳入Spring容器管理。

如果这些组件采用xml的bean定义来进行配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。Spring2.5引入了组件自动扫描机制,它可以在类路径下寻找标注了@Component,@Service,@Controrl,@Respository注解的类,并把这些类纳入Spring容器管理,它的作用和xml文件中bean节点的配置是一样的,要使用自动扫描机制,我们需要打开以下配置信息:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context"         
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  8.            
  9.           <context:component-scan base-package="xjj.test"/>  
  10. </beans>  
 <context:component-scan base-package="xjj.test"/>,说明Spring要扫描那个包下的bean,这里包含基包下的所有子包中的类。扫描这些类后,那么Spring怎么知道,哪些类要交给Spring容器来管理呢,这时候我们用到了注解,就是寻找标注了这些注解@Component,@Service,@Controrl,@Respository的类,当在类中发现了这些标记,Spring就会认为你要把这些类交给他来管理。

类上面添加的这些标记,就相当于配置文件中的bean节点。

@Service:用来标记业务层对象;

@Controrl:标注控制层,相当于Struts2中的action;

@Respository:用来标记数据引用对象(dao组件);

@Component:在项目中,有些组件归在以上三层都不像的时候,用着的泛指的组件。

目前,使用这四个注解都是一样,Spring还没有做相关区分,以后可能会有特殊处理。

通过注解标注的对象,在用getBean("beanName")获取时,默认将类型首字母小写后作为bean名称。

用@Service 注解,PersonService personService = (PersonService)ctx.getBean("personServiceBean");

使用的是实现类的名字,而不是接口类。

那默认值可以改吗?当然可以。

用@Service("personService")注解后,就可以用PersonService personService = (PersonService)ctx.getBean("personService");

注:默认是单例,如果需要改成原型,就要加@scope注解。

0 0
原创粉丝点击