使用@Component,@Service,@Controller,@Repositroy可以完成不用XML配置也可以将Java组件交给Spring容器
JavaBean代码如下:
package autoScan.dao;
public interface StudentDao {
public abstract void add();
}
@Repository
@Scope("singleton")
public class StudentDaoImple implements StudentDao {
// @PostConstruct用于配置初始化方法与XML中的init-method作用一致
@PostConstruct
public void myInit() {
System.out.println("初始化方法");
}
// @PreDestroy用于配置销毁方法与XML中的destroy-method作用一致
@PreDestroy
public void myDestroy() {
System.out.println("销毁方法");
}
public void add() {
System.out.println("autoScan.dao.imple.StudentDaoImple的add方法");
}
}
package autoScan.service;
public interface StudentService {
public abstract void save();
}
@Service("stuService")
public class StudentServiceImple implements StudentService {
@Resource(name = "studentDaoImple")
private StudentDao stuDao;
public void setStuDao(StudentDao stuDao) {
this.stuDao = stuDao;
}
public void save() {
stuDao.add();
}
}
那么XML中只需配置<context:component-scan>即可如下:
<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"> <!-- 通过在classpath自动扫描方式把组件纳入Spring容器中管理 --> <context:component-scan base-package="autoScan.dao"></context:component-scan> <context:component-scan base-package="autoScan.service"></context:component-scan> </beans>
说明:
/**
* 通过在classpath自动扫描方式把组件纳入Spring容器中管理
*
* @author 张明学 2010-6-3下午09:52:40
*/
public class AutoScanTest {
public static void main(String[] args) {
// 通过<context:component-scan base-package="autoScan.dao"/>将base-package内
// 寻找标注了@Component,@Service,@Controller,@Repositroy的bean纳入Spring的容器中
// @Repositroy:用于标注数据访问组件
// @Service:用于标注业务层
// @Controller:用于标注控制器
// @Component:用于标注其它的组件 (暂时这四个注解功能上没有什么区别)
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans5.xml");
// Bean的id默认为类名第一个字母小写,也可以@Service("stuService")进行修改
// 也可以通过@Scope("prototype")指定bean的作用域
// 也可以通过@PostConstruct指定初始化方法
// 也可以通过@PreDestroy指定销毁方法
System.out.println(ctx.getBean("studentDaoImple"));
System.out.println(ctx.getBean("stuService"));
StudentService stuService = (StudentService) ctx.getBean("stuService");
System.out.println(stuService);
System.out.println(ctx.getBean("studentDaoImple") == ctx
.getBean("studentDaoImple"));
ctx.close();
}
}