配置bean-加载bean-接受请求-调用bean
一、bean的配置
1.在xml文件中配置bean的基本格式:
<bean id="helloWorld" class="com.kang.spring.HelloWorld">
<!-- 为属性赋值 -->
<property name="user" value="kang"></property>
</bean>
id:通过id唯一标识bean
class:指定把哪个类关联为bean,使用全类名
在spring2.5之后支持注解配置bean(多按注解配置bean)
按功能进行bean的配置
@Component:泛指组件,对于有一般不好归类的java Bean使用
@Service:用于标注service层
@Controller:用于标注控制层(相当于servlet)
@Repository:用于标注Dao层
二、springXML文件的配置
使用注解后,通过xml的配置和扫描将bean加载到容器中。
自动扫描:spring的配置文件中添加:
<context:component-scan base-package=“自动扫描的包名“>
Spring在运行时就可以对指定的包中所有添加了Spring注解的bean自动扫描,注入,装配和初始化。
建立xml文件时按照功能模块将spring配置文件分开,例如Dao层配置到一个spring-dao.xml中,Service层配置到spring-service.xml中,springmvc配置到springmvc.xml中。在Maven工程中通过web.xml配置,使用通配符方式加载配置好的xml文件
classpath:spring/applicationContext-*.xml
classpath:spring/springmvc.xml