您的位置:首页 > 编程语言 > Java开发

Spring——AOP

2016-04-30 16:14 597 查看
  面向对象编程中,每一类都定义了一项明确的任务。然而这种编程也存在着缺陷。比如横切功能。一项功能可以影响系统的大部分。例如典型的日志记录功能,事物处理功能等。在处理日志,事物等功能方面,就用到AOP了。

AOP的常用术语有:

  通知(Advice):通俗的说就是要增加的额外的功能。

    Spring切面可以应用5种类型的通知:

    1、Before——在方法被调用之前调用通知

    2、After——在方法完成之后调用通知,无论方法执行是否成功。

    3、After-returning——在方法成功执行之后调用通知

    4、After-throwing——在方法抛出异常后调用通知

    5、Around——在方法之前或之后调用通知

  连接点(Jointpoint):通俗的说就是要在xx方法、异常、事件添加通知,xx就是一个连接点。

  切点(pointcut):通俗的说,由一个或多个连接点组成的集合。

  切面(Aspect):通俗的说就是通知和切点的接合体。

例子:

MyBean:

<span style="font-size:18px;">package com.spring.bean;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public void sayHello(){
System.out.println("hello!!!!");
}
}
</span>


MyOtherBean:

<span style="font-size:18px;">package com.spring.bean;
import org.springframework.stereotype.Component;
@Component
public class MyOtherBean {

public void sayHello2() throws InterruptedException{
Thread.sleep(1000);
System.out.println("hello!!!!!");
}
}
</span>
TestSpringAOP:

<span style="font-size:18px;">@Component
@Aspect
public class TestSpringAOP  {

@Before(value="execution(public * say*(..))")
public void before(JoinPoint joinPoint){
System.out.println("before-----"+joinPoint.getSignature().getName());
}
}
</span>
Client:

<span style="font-size:18px;">public class client {

public static void main(String[] args) throws InterruptedException {
BeanFactory applicationContext=new
ClassPathXmlApplicationContext("/applicationContext.xml");
MyBean myBean= applicationContext.getBean(MyBean.class);
myBean.sayHello();

MyOtherBean myOtherBean=applicationContext.getBean(MyOtherBean.class);
myOtherBean.sayHello2();

}

}</span>
applicationContext.xml:
<span style="font-size:18px;"><?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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" >
<context:component-scan base-package="com.spring"></context:component-scan>
<context:annotation-config/>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
</span>


运行结果:

before-----sayHello

hello!!!!

before-----sayHello2

hello!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java Spring