IOC及Bean容器

来源:互联网 发布:mac怎么切换独立显卡 编辑:程序博客网 时间:2024/06/17 00:05

最近在学习慕课网上的http://www.imooc.com/learn/196,讲的很好。这里结合网上的资料还有《Spring in Action》 做的一点笔记

---

IOC 控制反转 ,就是把控制权交给容器
相当于住房子,我们自己不用建筑房子,而是去找中介 租或者买房。

Bean ,Spring里的Java对象都是Bean
Spring 注入是指在启动Spring容器加载Bean配置的时候完成对变量的赋值行为,。
常用的两种注入方式
设值注入
构造注入

现在看设值注入的配置:

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="injectionService" class="com.xyf.InjectionServiceImpl">
<property name="injectionDAO" ref="injectionDao"></property>
</bean>
<bean id="injectionDao" class="com.xyf.InjectionDaoImpl"></bean>
</beans>

Spring 配置文件的根元素是来源于Spring beans命名空间所定义的<beans>元素。
配置完毕后我们需要一个Spring容器来测试代码。Spring的容器有BeanFactoryApplicationContext

BeanFactory作为最简单的容器提供了基础的依赖注入和Bean装配服务。当我们需要更高级的框架服务时,选择ApplicationContext更合适

在例子代码中我们采用了ApplicationContext来实现。
先实例化ApplicationContext

context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
context.start();

容器通过beanid 得到bean,调用方法。最后destroy方法回收容器内容。

附上 UnitTestBase的代码

package com.xyf;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
public class UnitTestBase {
private ClassPathXmlApplicationContext context;
private String springXmlpath;
public UnitTestBase() {}
public UnitTestBase(String springXmlpath) {
this.springXmlpath = springXmlpath;
}
@Before
public void before() {
if (StringUtils.isEmpty(springXmlpath)) {
springXmlpath = "classpath*:spring-*.xml";
}
try {
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
context.start();
} catch (BeansException e) {
e.printStackTrace();
}
}
@After
public void after() {
context.destroy();
}
@SuppressWarnings("unchecked")
protected <T extends Object> T getBean(String beanId) {
try {
return (T)context.getBean(beanId);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}
protected <T extends Object> T getBean(Class<T> clazz) {
try {
return context.getBean(clazz);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
}
}

PS : 使用Junit测试spring项目
test目录只需要和main一样的目录就可以了
Junit项目会有一篇笔记专门介绍。

0 0