1.关于依赖注入(控制反转):
在依赖注入的模式下,创建被调用者的工作不再由调用者来完成,因此称为控制反转;创建被调用者实例的工作通常由spring窗口完成,然后注入调用者,因此也称为依赖注入。
如:ApplicationContext.xml的部分内容:
<bean id="person" class="Person">
<property name="name" value="wawa"/>
</bean>
在调用当中:
Person p = (Person)ctx.getBean("person");
p.info();
以三种情况来说明依赖注入:
原始的情况下,如果一个人要一把斧头,那么只能自己去生产。
工厂模式下,可以从工厂去买,而不用自己生产。
在依赖注入的模式下,都不用管斧头是从哪个工厂生产的,到需要的时候会由一个分配的直接分配给他。
所谓依赖注入,就是指程序运行过程当中,如果要调用另一个对象协助时,无须在代码当中创建被调用者,而是依赖于外部的注入。
2.两种注入方式:
1.设值注入
像上面的方式
2.构造注入
<bean id="chinese" class="lee....">
<constructor-arg ref="steelAxe"/>
</bean>
<bean id="steelAxe" class="..."/>
3.BeanWrapper接口:
- 操作 bean
BeanWrapper接口其实就是通过一个Java bean的对象来构造一个BeanWrapper对象,通过这个对象可以对Java Bean的对象中的属性进行设置,而不用去调用Java Bean对象的相关函数。其调用过程如下:
TestBean bean = new TestBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("name","liuqi");
//这里就相当于调用了bean.setName("liuqi");
- 使用BeanWrapper的PropertyEditors包来转换属性:
有时候为了使用方便,我们要以另外一种形式展现对象的属性。为达到这样的目的,我们可以编写自定义编辑器,使其继承java.beans.PropertyEditor类型,并将自定义编辑器注册到BeanWrapper上,通过注册,BeanWrapper将知道如何把属性转换成所需类型的信息。
public class Person {
public void setBirthDay(Date d);
public Date getBirthDay();
}
/** and some other method */
public void doIt() {
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
// CustomDateEditor located in org.springframework.beans.propertyeditors
// true indicated that null values are NOT allowed
CustomDateEditor editor = new CustomDateEditor(df, false);
Person p = new Person();
BeanWrapper bw = new BeanWrapper(p);
bw.registerCustomEditor(editor);
// this will convert the String to the desired object type: java.util.Date!
bw.setPropertyValue("birthDay", "22-12-1966");}
4.BeanFactory
a.使用:
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("hello.xml"));
TestBean bean= (TestBean)factory.getBean("testBean");
b.
5.applicationContext
A.它与BeanFactory不同的地方在于:
a.附加了更多的功能
b.在上下文启动之后载入所有的单实例Bean,而BeanFactory是在getBean调用的时候才载入实例。
B. applicationContext的有一种实现:
a.ClassPathXmlApplicationContext:从类路径的XML文件当中载入
b.FileSystemXMLApplicationContext:从文件系统的XML文件当中载入
c.XmlWebApplicationContext:从Web路径的XML文件当中载入
6.AOP
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www..." ... http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="testAspect" class="..."/> <aop:config> <aop:aspect ref="testAspect"> <aop:pointcut id="test" expression="execution(* *.fun()) and target(bean)"/> <aop:before method="before" pointcut-ref="test" arg-names="bean"/> <aop:after-returning" .../> </aop:aspect> </aop:config> </beans>
附:spring教程:
1.spring framework :http://www.redsaga.com/spring_ref/2.0/html/