含义:
IOC是一种思想,它的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的;Spring中对象的属性字段赋值,这称为依赖注入DI(Dependency Injection)。
依赖注入的分类:
xml注入:必须要有setter方法,所以这种注入方式又称之为属性注入或setter方法注入;
1.字段的类型和被注入的对象的类型要一致
2.xml方式必须要setter方法(底层就是通过反射和调用setter方法复制的)
<bean id="otherBean" class="cn.itshow.bean.OtherBean"></bean>
<bean id="myBean" class="cn.itshow.bean.MyBean">
<!-- 属性:bean属性,如果该属性是字符串或基本类型的值,直接写value -->
<property name="name" value="易小川"></property> <!-- 实际开发中:这种情况非常少 -->
<!-- ref:因为注入的是一个对象 -->
<property name="time" ref="date"></property> <!-- 实际开发中:这种情况非常少 -->
<!-- ref:从容器中去找一个类型匹配【当前属性的类型与被注入对象的类型(可以是其子类)】的对象赋值给当前字段 -->
<property name="bean" ref="otherBean"></property> <!-- 实际开发中:这种情况非常多 -->
</bean>
注解注入
将注解写在setter方法上,也可以写在字段上,如果写在字段上可以不需要setter方法;
@Autowired:由Spring提供的注解
@Resource:由J2EE提供,需要导入包javax.annotation.Resource,spring支持这个注解
@Autowired
private MyBean bean;
@Resource
private Tomato t;
@Resource
private IUserDao dao;
@Resource
private IUserService service;
Spring测试
-
在Junit之上,Spring做了进一步的封装,这个集成的测试模块叫Spring-test,底层还是Junit4(所以还是需要junit4包)
-
spring测试以注解的方式加载配置文件和实例化容器对象,简化了代码,提高了测试效率。
实现spring测试: -
导包:spring-aop-4.1.2.RELEASE.jar,spring-test-4.1.2.RELEASE.jar
-
编写测试方法:
-
注意使用Spring测试需要加载spring配置文件和启动Springtest
-
加载上下文配置 – 配置是写在配置文件中的
@ContextConfiguration(“classpath:applicationContext.xml”)
启动Springtest
@RunWith(SpringJUnit4ClassRunner.class)//启动Springtest 对junit4封装,必须导入junit4的jar包
//加载上下文配置 -- 配置是写在配置文件中的
@ContextConfiguration("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)//启动Springtest 对junit4封装,必须导入junit4的jar包
public class SpringTest {
// 去容器中查询MyBean类型的对象赋值给当前字段,如果没有找到报错
@Autowired
private MyBean mybean;
@Resource
private Tomato t;
@Test
public void testBean(){
System.out.println(mybean);
System.out.println(t);
}
}