简介
Spring中有一个关键的组件AOP框架,然而Spring IOC容器并不依赖与AOP,也就是说可以不用AOP,他只是对项目的解耦更加细致,明确
AOP-另一种编程思想
当我们需要对分散的对象引入公共行为的时候,OOP并不能解决这个问题,也就是说,OOP允许实现从上到下,不适合从左到右的关系,它作为一种横切的技术,解刨开对象的内部,将那些与业务无关,却被业务模块共同调用或责任封装起来.
实现:
基于xml
1.创建目标对象
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running");
}
}
2.创建切面对象
public class MyAspect {
public void brfore(){
System.out.println("前置增强....");
}
public void afterReturning(){
System.out.println("后置增强");
}
//ProceedingJoinPonit:正在执行的连接点=切点
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强");
Object proced=pjp.proceed();//切点方法
//切点方法
System.out.println("环绕后增强");
return proced;
}
public void afterThrowing(){
System.out.println("异常抛出");
}
创建ApplicationContext.xml声明Bean,和切面
<!--目标对象 -->
<bean id="target" class="aop_1.Target"/>
<!--切面对象 -->
<bean id="myAspect" class="aop_1.MyAspect"/>
<!--配置织入:告诉spring框架 那些方法需要切入( 增强) -->
<aop:config>
<!--声明切面 -->
<aop:aspect ref="myAspect">
<aop:before method="brfore" pointcut="execution(public void aop_1.Target.save())" ></aop:before>
<aop:around method="around" pointcut="execution(public void aop_1.Target.save())"></aop:around>
<aop:after-throwing method="afterReturning" pointcut="execution(public void aop_1.Target.save())"></aop:after-throwing>
</aop:aspect>
</aop:config>
测试实现:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:Application.xml")
public class AopTest_1 {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
从这个流程可以很直观的看出基于spring容器,很简单的实现了增强操作.而注解只是稍加改变好一点.