在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会让配置文件很臃肿,查找及维护起来不方便.Spring2.5为引入了自动扫描机制,它可以在类路径下寻找标注了@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中,它的作用和在xml文件中使用bean节点配置组件是一样的.
@Service用于标注业务层组件
@Repository用于标数据库层组件
@Controller用于标注控制层组件
@Component泛指组件,当不能分清是哪层组件时使用
autoscanbeans.xml
<?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.skymr.spring.test"/>
</beans>
package com.skymr.spring.test.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.skymr.spring.test.dao.UserInfoDao;
import com.skymr.spring.test.service.UserInfoService;
@Service("userInfoService")
public class UserInfoServiceBean implements UserInfoService{
@Resource
private UserInfoDao userInfoDao;
private String name;
public UserInfoServiceBean(UserInfoDao userInfoDao, String name){
this.userInfoDao = userInfoDao;
this.name = name;
}
public void setName(String name){
this.name = name;
}
public UserInfoServiceBean(){
}
public void delete() {
userInfoDao.delete();
}
public void find() {
userInfoDao.find();
}
public void save() {
userInfoDao.save();
}
public void update() {
userInfoDao.update();
}
}
package com.skymr.spring.test.dao.impl;
import org.springframework.stereotype.Repository;
import com.skymr.spring.test.dao.UserInfoDao;
@Repository("userInfoDao")
public class UserInfoDaoBean implements UserInfoDao{
//用于判别bean
private String name;
public void setName(String name){
this.name = name;
}
public void delete() {
System.out.println(name + "删除一个用户");
}
public void find() {
System.out.println(name + "查找一个用户");
}
public void save() {
System.out.println(name + "保存一个用户");
}
public void update() {
System.out.println(name + "更新一个用户");
}
}
@org.junit.Test
public void springIOCTestAuto(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("autoscanbeans.xml");
com.skymr.spring.test.service.UserInfoService userInfoService = (com.skymr.spring.test.service.UserInfoService) ctx.getBean("userInfoService");
userInfoService.save();
}