spring2.5引入了组件自动扫描机制,
他可以在类路径底下寻找标注了
@Component、@Service、@Controller、@Repository注解的类,
并把这些类纳入进spring容器中管理。
@Service用于标注业务层组件、
@Controller用于标注控制层组件(如struts中的action)、
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,需要打开以下配置信息:
<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.dwt1220"/>
</beans>
<?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.dwt1220"/>
</beans>
PersonService.java 接口
package com.dwt1220;
public interface PersonService {
public abstract void save();
}
PersonServiceBean.java
package com.dwt1220;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service("personServicexxx")//设置bean的id。默认类名的第一个字母小写personServiceBean
@Scope("prototype")//设置bean的作用域。默认singleton
public class PersonServiceBean implements PersonService {
@PostConstruct //设置类的初始化方法,同bean标签的init-method=""设置
public void init() {
System.out.println("初始化");
}
@PreDestroy//设置类的销毁方法,同bean标签的destroy-method=""设置
public void destory() {
System.out.println("关闭资源");
}
public void save() {
System.out.println("personService的save()方法");
;
}
}