其实说起Spring,首先想到的是这个一开源的轻量级框架。
它的核心为控制反转(依赖注入)和面向切面编程(AOP),当然了它还为Struts和Hibernate框架
的整合提供了机制。除此之外,Spring还可以对事务进行管理,又分为编程事务管理和声明事务管理。
下面逐次说明:
控制反转(Invasion Of Control):
这是Spring的核心,其中心思想是,由spring来负责控制对象的生命周期和对象间的关系。
依赖注入(Dependency Injection):是一个程序的设计模式和架构模型。一些情况也可称为IoC,控制反转和依赖注入的基本思想是
把对象对类的依赖从内部转到外部,以此减少依赖。
面向切面编程(AOP):
首先,要学好Aop必须明白动态代理。
粘贴了一个示例:
View Code
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName">
<!-- ==============================利用spring自己的aop配置================================ -->
<!-- 声明一个业务类 -->
<bean id="baseBusiness" class="aop.base.BaseBusiness" />
<!-- 声明通知类 -->
<bean id="baseBefore" class="aop.base.advice.BaseBeforeAdvice" />
<bean id="baseAfterReturn" class="aop.base.advice.BaseAfterReturnAdvice" />
<bean id="baseAfterThrows" class="aop.base.advice.BaseAfterThrowsAdvice" />
<bean id="baseAround" class="aop.base.advice.BaseAroundAdvice" />
<!-- 指定切点匹配类 -->
<bean id="pointcut" class="aop.base.pointcut.Pointcut" />
<!-- 包装通知,指定切点 -->
<bean id="matchBeforeAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut">
<ref bean="pointcut" />
</property>
<property name="advice">
<ref bean="baseBefore" />
</property>
</bean>
<!-- 使用ProxyFactoryBean 产生代理对象 -->
<bean id="businessProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理对象所实现的接口 ,如果有接口可以这样设置 -->
<property name="proxyInterfaces">
<value>aop.base.IBaseBusiness</value>
</property>
<!-- 设置目标对象 -->
<property name="target">
<ref local="baseBusiness" />
</property>
<!-- 代理对象所使用的拦截器 -->
<property name="interceptorNames">
<list>
<value>matchBeforeAdvisor</value>
<value>baseAfterReturn</value>
<value>baseAround</value>
</list>
</property>
</bean>
</beans>
代码出处:http://www.cnblogs.com/yanbincn/archive/2012/08/13/2635413.html
事务的处理:
在以往的JDBCTemplate中事务提交成功,异常处理都是通过Try/Catch 来完成,而在Spring中。Spring容器集成了TransactionTemplate,她封装了所有对事务处理的功能,包括异常时事务回滚,操作成功时数据提交等复杂业务功能。这都是由Spring容器来管理,大大减少了程序员的代码量,也对事务有了很好的管理控制。Hibernate中也有对事务的管理,hibernate中事务管理是通过SessionFactory创建和维护Session来完成。而Spring对SessionFactory配置也进行了整合,不需要在通过hibernate.cfg.xml来对SessionaFactory进行设定。这样的话就可以很好的利用Sping对事务管理强大功能。避免了每次对数据操作都要现获得Session实例来启动事务/提交/回滚事务还有繁琐的Try/Catch操作。这些也就是Spring中的AOP(面向切面编程)机制很好的应用。一方面使开发业务逻辑更清晰、专业分工更加容易进行。另一方面就是应用Spirng AOP隔离降低了程序的耦合性使我们可以在不同的应用中将各个切面结合起来使用大大提高了代码重用度 。