Spring自动扫描和管理Bean 在大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会使配置文件显得很臃肿,查找和维护起来不方便。

        Spring自动扫描和管理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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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 
		 http://www.springframework.org/schema/tx 
		 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	
	<context:component-scan base-package="com.zpring"></context:component-scan><!--base-package为需要扫描的包(包括子包)-->
</beans> 

@Service用于标注业务层的组件,

@Controller用于标注控制层组件(如struts中的action),

@Repository用于标注数据访问组件,即DAO组件,

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

import org.springframework.stereotype.Service;

import com.zpring.dao.PersonDao;
import com.zpring.service.UserService;

@Service
// 把这个类交给spring管理,作为服务。
public class UserServiceImpl implements UserService {
	private PersonDao personDaoBean;

	public void show() {
		personDaoBean.show();
	}

	public void setPersonDaoBean(PersonDao personDaoBean) {
		this.personDaoBean = personDaoBean;
	}


	public PersonDao getPersonDaoBean() {
		return personDaoBean;
	}
}

其中userService是在配置文件中配置的bean的id。但是如今我们并没有id这个属性,在spring2.5中,默认的id是类的名称,但是开后是小写,也就是userServiceImpl。

如果我们想自己命名的话,则只需在注解后加上括号,里面写入你希望的名字,如@Service("userService")。
在spring中默认的是只生成一个bean实例,如果我们想每次调用都产生一个实例,则标注需如下配置@Service @Scope("prototype")

猜你喜欢

转载自blog.csdn.net/hxb_hexiaobo/article/details/77189749