IOC和DI
IOC inverse of control 控制反转
1 Bean的生成由程序员控制到由容器控制
2 由控制程序的实现,到控制接口
DI Dependence Injection
依赖注入
Spring的注入方式:
1.getter和setter
2.构造方法注入
3.接口注入
其中第一个是最常用的一个
第二个需要配置参数,注意在配置的时候如果使用的是<ref/>
那么相当于使用的是一个已经存在的bean
而如果使用的是<bean />标签的话,就相当于是要重新的生成
一个bean来使用.
Spring在配置的时候,既可以使用id也可以使用name其中name是
后来采用的,而刚开始的时候就使用的是id所以也就没有再去改变
它
区别name里面可以含有特殊字符.
简单属性的注入:
简单属性的注入可以使用的是
<property name="" value="">
如果注入的是一个bean就使用
<property ref=""/>
一般情况下简单属性配置在Spring的配置文件中的情况很少见
只有在配置特殊的东西的时候才会使用的,比如配置数据源.
Spring在配置Bean的时候有一个scope选项包括:
singleton:单例,无论拿多少都是同一个对象
prototype:原型,每拿一次都会创造一个新的.
默认情况下是singleton,但是它推荐的是使用prototype.
<?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:annotation-config />
<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
</bean>
<bean id="u2" class="com.bjsxt.dao.impl.UserDAOImpl">
</bean>
<bean id="userService" class="com.bjsxt.service.UserService" >
</bean>
</beans>
xml文件分析:
xmlns="http://www.springframework.org/schema/beans"
这句话代表的是在本xml文件中出现的没有任何前缀的标签的命名空间在"http://www.springframework.org/schema/beans"里面
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
代表在本xml文件中前缀为xsi的标签的命名空间为"http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
代表的是以context开头的标签的命名空间为"http://www.springframework.org/schema/context"
注意http://www.springframework.org/schema/beans代表的是标签的键
而
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
代表的是标签的值.