1、xml文件配置,引入context命名空间:
<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.springtest"/>
</beans>
2、xml文件中添加context:component-scan标签
<context:component-scan base-package="com.springtest"/>
- base-package:需要扫描的包及其子包
- 扫描元素时,AutowiredAnnotationBeanPostProcessor 和CommonAnnotationBeanPostProcessor会隐式地被包括进来,不需要在XML中提供任何bean配置元数据
3、标注组件
- @Service标注业务组件
- @Controller标注控制层组件
- @Repository标注数据访问组件
- @Component泛指组件,当组件不好归类、用这个注解进行标注
@Service
public class ServiceImpl implements Service {
}
@Repository
public class DaoImpl implements Dao {
}
//自定义bean名称使用@Service(“myDAO”),类名(头字母小写)
//bean默认是单例的,改变使用@Scope("prototype")
@Service("myDAO")
@Scope("prototype")
public class myDAOImpl extends HibernateDaoSupport implements myDAO{
//指定初始化方法和销毁方法
@PostConstruct
public void init() {
}
@PreDestroy
public void destory() {
}
}
<bean id="myDAO"
class="com.springtest.myDAOImpl" scope="prototype">
......
</bean>