`

知识点六:自动扫描方式把组件纳入(注册到)spring容器中管理

阅读更多
前面我们都是使用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="cn.itcast"/>
</bean>
其中,base-package就是要扫描的包以及子包

@Service用于标注业务层组件
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问层组件,即DAO
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

import org.springframework.stereotype.Repository;
@Repository
public class PersonDao {
	public void save() {
		System.out.println("save");		
	}
}


这样,当容器扫描到此类的时候就纳入了容器里。

import org.springframework.stereotype.Service;
import cn.itcast.dao.PersonDao;
import cn.itcast.service.PersonService;
@Service
public class PersonServiceBean implements PersonService {
	@Resource private PersonDao personDao;
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}
	public void save()
	{
		personDao.save();
	}
}


这样我们如何调用此bean?也没有配置文件里的id.spring规范这样规定:在自动扫描的情况下,要得到一个容器管理的bean,可以提供bean的全名,但是第一个字符小写!

ApplicationContext ctx = new 
ClassPathXmlApplicationContext("beans.xml");
PersonService personService = 
(PersonService)ctx.getBean("personServiceBean ");
personService.save();



当然,可以自己指定被调用的时候用的名称(默认都是单例模式,即scope=singleton)

@Service(“personService”)
public class PersonServiceBean implements PersonService


如果要改成原型模式怎么做呢?这样

@Service(“personService”) @Scope(“prototype”)
public class PersonServiceBean implements PersonService


但是这样如何实现指定初始化和销毁方法呢?spring采用的是注解方式!

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

	@PostConstruct
	public void init(){
		System.out.println("初始化");
	}
	@PreDestroy
	public void destroy(){
		System.out.println("销毁");
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics