loc(控制反转)是spring的两大核心思想之一,他是将java bean 的创建以及生命周期的实现和控制交由容器来管理。这样做的缺点是耦合性较高,不利于程序的扩展。
使用spring的步骤
1)新建maven项目(书写三要素)
2)加入spring的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
3)编写spring的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.westos.dao.UserDao">
</bean>
</beans>
4)创建对象
如果bean没有无参构造,就需要对构造方法进行赋值。
<constructor-arg index="参数下标" value="值"/>
标签的意义分析:
scope ----是否为单例(默认为单例,如果需要修改为多例,则为prototype)
init-method ----初始化的方法(该方法必须在bean中)
destory-method ---- 销毁的方法(该方法必须在bean中)