Spring学习(6) 通过在classpath自动扫描方式把组件纳入Spring容器中管理
Spring学习(六) 通过在classpath自动扫描方式把组件纳入Spring容器中管理
之前我们都是使用XML的bean定义来配置组件,在大项目中,通常会使用很多组件,如果这些组件都采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不方便。Spring2.5为我们引入了组件自动扫描机制,可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进Spring容器中管理。它的作用和在xml文件使用bean节点配置组件都是一样的。要使用自动扫描机制,我们需要打开以下配置信息:
其中,base-package="com.bill"为需要扫描的包(包含子包)。@Service用于标注业务层组件,@Controller用于标注控制层组件(入struts中的action),@Repository用于标注数据访问组件,即DAO组件,而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
例如:
数据访问层代码:
业务层代码:
测试代码:
之前我们都是使用XML的bean定义来配置组件,在大项目中,通常会使用很多组件,如果这些组件都采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不方便。Spring2.5为我们引入了组件自动扫描机制,可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进Spring容器中管理。它的作用和在xml文件使用bean节点配置组件都是一样的。要使用自动扫描机制,我们需要打开以下配置信息:
<?xml version="1.0" encoding="UTF-8"?> <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="com.bill"/> </beans>
其中,base-package="com.bill"为需要扫描的包(包含子包)。@Service用于标注业务层组件,@Controller用于标注控制层组件(入struts中的action),@Repository用于标注数据访问组件,即DAO组件,而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
例如:
数据访问层代码:
package com.bill.dao.impl; import org.springframework.stereotype.Repository; import com.bill.dao.PersonDao; @Repository public class PersonDaoBean implements PersonDao { public void add() { System.out.println("this is add() of PersonDaoBean"); } }
业务层代码:
package com.bill.impl; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.bill.PersonService; import com.bill.dao.PersonDao; /** * if Scope is prototype, it means new the object when using this bean * @author Bill * */ @Service("personService") //指定bean名字 //@Service("personService") @Scope("prototpye")//指定bean名字,并且每调用这个类,就创建新的对象 //@Service //默认bean的名称为类名的第一个字母小写,如personServiceBean public class PersonServiceBean implements PersonService { private PersonDao personDao; public void save(){ personDao.add(); } //当Spring容器装载前执行初始化方法 @PostConstruct public void init(){ System.out.println("init() function"); } //当Spring容器卸载之前执行释放资源方法 @PreDestroy public void destroy(){ System.out.println("destroy resource"); } }
测试代码:
AbstractApplicationContext act = new ClassPathXmlApplicationContext("beans.xml"); PersonService personService = (PersonService)act.getBean("personService"); personService.save(); act.close();